package monkey

import (
	"goqs/controllers"
	"goqs/dbsql"
	"goqs/models"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

// @Tags Monkey相关 /api/monkey/v1/
// @Summary 新建Monkey任务
// @Description 新建Monkey任务，创建成功后将会发送指令到monkey服务，初始status为WAITTING-等待中
// @accept x-www-form-urlencoded
// @Param project formData string false "项目名"
// @Param package_url formData string false "测试包下载链接"
// @Param package_name formData string true "应用包名"
// @Param launch_activity formData string false "启动activity页"
// @Param device_amount formData string false "运行设备数，默认1台"
// @Param platform formData string true "平台adr/ios"
// @Param run_time formData string false "运行时间（s），默认两小时（7200s）"
// @Param creator formData string false "任务创建者"
// @Param mode formData string false "调用服务的方式，0-cli模式/1-api模式，默认cli"
// @Success 200 {object} models.Response "返回创建的任务id"
// @Router /api/monkey/v1/create_task [post]
func CreateTask(c *gin.Context) {
	rsp := controllers.NewResponse()

	db, err := dbsql.GetConn(dbsql.DSN)
	if err != nil {
		rsp.Error(err.Error())
		c.JSON(http.StatusOK, rsp)
	}

	var task models.MonkeyTask
	task.Project = c.PostForm("project")
	task.PackageURL = c.PostForm("package_url")
	task.PackageName = c.PostForm("package_name")
	task.LaunchActivity = c.PostForm("launch_activity")
	task.DeviceAmount = cast.ToInt(c.DefaultPostForm("device_amount", "1"))
	task.Platform = c.PostForm("platform")
	task.RunTime = cast.ToInt(c.DefaultPostForm("run_time", "7200"))
	task.Creator = c.PostForm("creator")
	task.Status = "WAITTING"

	// || task.Creator == ""
	if task.PackageName == "" || task.LaunchActivity == "" ||
		task.DeviceAmount <= 0 || task.Platform == "" ||
		task.RunTime <= 10 || task.PackageURL == "" {
		rsp.Error("get formdata error")
		rsp.Data = task
		c.JSON(http.StatusOK, rsp)
		return
	}

	db.Model(models.MonkeyTask{}).Create(&task)
	if db.Error != nil {
		rsp.Error(db.Error.Error())
		c.JSON(http.StatusOK, rsp)
	}

	rsp.Success()
	rsp.Data = task
	c.JSON(http.StatusOK, rsp)

	go runAndroidMonkeyCmd(task)
}

// @Tags Monkey相关 /api/monkey/v1/
// @Summary 更新Monkey任务状态
// @Description 更新Monkey任务状态，进行中为RUNNING，已完成为FINIASHED，如有错误为ERROR
// @accept x-www-form-urlencoded
// @Param task_id formData int true "项目名"
// @Param status formData string false "要更新的任务状态"
// @Success 200 {object} models.Response "返回更新后的任务信息"
// @Router /api/monkey/v1/task/status [post]
func UpdateTaskStatus(c *gin.Context) {
	rsp := controllers.NewResponse()

	task_id := cast.ToInt(c.PostForm("task_id"))
	status := c.PostForm("status")
	if task_id <= 0 {
		rsp.Error("task_id error")
		c.JSON(http.StatusOK, rsp)
		return
	}

	db, err := dbsql.GetConn(dbsql.DSN)
	if err != nil {
		rsp.Error(err.Error())
		c.JSON(http.StatusOK, rsp)
	}
	var task models.MonkeyTask
	db.Where("id = ?", task_id).Find(&task)
	if task.Id <= 0 {
		rsp.Error("任务不存在")
		c.JSON(http.StatusOK, rsp)
		return
	}
	task.Status = status
	db.Save(&task)

	rsp.Success()
	rsp.Data = task
	c.JSON(http.StatusOK, rsp)
}

// @Tags Monkey相关 /api/monkey/v1/
// @Summary 获取任务列表
// @Description 获取任务列表
// @accept x-www-form-urlencoded
// @Param page_size query int false "每页大小,默认为10"
// @Param page_index query int false "第几页，默认为第一页"
// @Success 200 {object} models.Response "返回更新后的任务信息"
// @Router /api/monkey/v1/tasks [get]
func GetTasks(c *gin.Context) {
	var rsp models.Response
	var p models.Page

	pageIndex, err := strconv.Atoi(c.DefaultQuery("page_index", "1"))
	if rsp.CheckErr(err) {
		c.JSON(http.StatusOK, rsp)
		return
	}
	p.Index = pageIndex
	pageSize, err := strconv.Atoi(c.DefaultQuery("page_size", "10"))
	if rsp.CheckErr(err) {
		c.JSON(http.StatusOK, rsp)
		return
	}
	p.Size = pageSize

	db, err := dbsql.GetConn(dbsql.DSN)
	if rsp.CheckErr(err) {
		c.JSON(http.StatusOK, rsp)
		return
	}
	defer dbsql.Close(db)

	var list []models.MonkeyTask

	db = db.Model(&models.MonkeyTask{})
	var count int64
	db = db.Count(&count)
	db = dbsql.SetPageQuery(db, pageIndex, pageSize)

	db.Order("id desc").Find(&list)

	p.MaxPage = count/(int64(p.Size)+1) + 1
	p.List = list
	p.Total = int(count)

	rsp.Success()
	rsp.Data = p
	c.JSON(http.StatusOK, rsp)
}
