package service

import (
	"strconv"

	"github.com/gin-gonic/gin"

	"github.com/pingcap-inc/clinic/pkg/api/common"
	apiErr "github.com/pingcap-inc/clinic/pkg/api/error"
	_const "github.com/pingcap-inc/clinic/pkg/const"
)

type GetTaskStatusParam struct {
	ClusterID string
	OrgID     uint64
	StartTime int64
	EndTime   int64
	TaskType  _const.TaskType
}

func (p *GetTaskStatusParam) validate(maxDataRange int64) error {
	if len(p.ClusterID) == 0 {
		return apiErr.ErrBadRequest.New("cluster is required")
	}
	if p.StartTime >= p.EndTime {
		return apiErr.ErrBadRequest.New("bad timestamp parameter")
	}

	if p.EndTime-p.StartTime > maxDataRange {
		return apiErr.ErrBadRequest.New("timestamp range is too long")
	}

	if !p.TaskType.Validate() {
		return apiErr.ErrBadRequest.New("unsupport data_type")
	}
	return nil
}

func (p *GetTaskStatusParam) Init(c *gin.Context) error {
	var err error
	p.ClusterID = c.Query("cid")
	p.OrgID, err = strconv.ParseUint(c.Query("oid"), 10, 64)
	if err != nil {
		return apiErr.ErrBadRequest.New("organization is required")
	}
	p.StartTime, err = strconv.ParseInt(c.Query("startTime"), 10, 64)
	if err != nil {
		return apiErr.ErrBadRequest.New("startTime is bad parameter")
	}
	p.EndTime, err = strconv.ParseInt(c.Query("endTime"), 10, 64)
	if err != nil {
		return apiErr.ErrBadRequest.New("startTime is bad parameter")
	}
	dataType, err := strconv.ParseInt(c.Query("data_type"), 10, 64)
	if err != nil {
		return apiErr.ErrBadRequest.New("bad data_type parameter")
	}
	p.TaskType = common.ConverToTaskType(common.APIDataType(int(dataType)))
	return nil
}
