package api

import (
	"easyvqd/internal/conf"
	"easyvqd/internal/core/host"
	"easyvqd/internal/core/vqd"
	"fmt"
	"git.lnton.com/lnton/pkg/reason"
	"github.com/gin-gonic/gin"
	"log/slog"
	"strconv"
)

func (a VqdTaskAPI) findVqdPollingChannel(c *gin.Context, in *host.FindChannelsInput) (any, error) {
	out, err := a.HostCore.FindChannels(c, in)
	if err != nil {
		return nil, err
	}
	rows := make([]map[string]interface{}, 0)
	for _, item := range out.Items {
		row := make(map[string]interface{})
		row["name"] = item.Name
		row["id"] = item.ID
		row["status"] = item.Status
		row["protocol"] = item.Protocol
		row["device_name"] = item.DeviceName
		row["is_polling"] = false
		chnInfo, errs := a.core.GetPollingChannelID(c.Request.Context(), item.ID)
		if errs == nil && chnInfo != nil && chnInfo.ChannelID != "" {
			row["is_polling"] = true
		}
		rows = append(rows, row)
	}

	return gin.H{"items": rows, "total": out.Total}, nil
}
func (a VqdTaskAPI) findVqdPolling(c *gin.Context, in *vqd.FindVqdPollingInput) (any, error) {
	items, total, err := a.core.FindVqdPolling(c.Request.Context(), in)
	rows := make([]map[string]interface{}, 0)

	for _, item := range items {
		row := make(map[string]interface{})
		row["name"] = item.Name
		row["channel_name"] = item.ChannelName
		row["channel_id"] = item.ChannelID
		row["task_template_id"] = item.TaskTemplateID
		row["id"] = item.ID
		row["status"] = a.vqdSdkCore.HasRunningTask(item.ChannelID)
		rows = append(rows, row)
	}

	return gin.H{"items": rows, "total": total}, err
}
func (a VqdTaskAPI) getVqdPolling(c *gin.Context, _ *struct{}) (any, error) {
	ID, _ := strconv.Atoi(c.Param("id"))
	item, err := a.core.GetVqdPolling(c.Request.Context(), ID)
	if err != nil {
		return nil, reason.ErrServer.SetMsg(fmt.Sprintf(`find vqd polling [%d] err [%s]`, ID, err.Error()))
	}
	row := make(map[string]interface{})
	row["name"] = item.Name
	row["channel_name"] = item.ChannelName
	row["channel_id"] = item.ChannelID
	row["task_template_id"] = item.TaskTemplateID
	row["id"] = item.ID
	row["status"] = a.vqdSdkCore.HasRunningTask(item.ChannelID)
	return gin.H{"data": row}, nil
}
func (a VqdTaskAPI) addVqdPolling(c *gin.Context, data *vqd.AddVqdPollingAllInput) (any, error) {

	for _, item := range data.Items {
		task, err := a.core.AddVqdPolling(c.Request.Context(), &item)
		if err != nil {
			slog.Error(fmt.Sprintf(`add vqd polling err [%s]`, err.Error()))
		} else {
			errs := a.vqdSdkCore.AddPollingTask(task)
			if errs != nil {
				slog.Error(fmt.Sprintf(`add vqd polling task err [%s]`, err.Error()))
			}
		}

	}

	return gin.H{"data": "OK!"}, nil
}

func (a VqdTaskAPI) editPollingConf(c *gin.Context, in *vqd.EditPollingConfInput) (any, error) {
	a.cfg.VqdConfig.PollingTemplate = in.PollingTemplate
	a.cfg.VqdConfig.PollingNum = in.PollingNum
	a.cfg.VqdConfig.PollingTime = in.PollingTime
	err := conf.WriteConfig(a.cfg, a.cfg.ConfigDirPath())
	if err != nil {
		return nil, err
	}
	a.vqdSdkCore.UpdatePollingTask()
	return in, nil
}
func (a VqdTaskAPI) getPollingConf(_ *gin.Context, _ *struct{}) (vqd.GetPollingConfOutput, error) {
	confMutex.Lock()
	defer confMutex.Unlock()

	return vqd.GetPollingConfOutput{
		PollingNum:      a.cfg.VqdConfig.PollingNum,
		PollingTime:     a.cfg.VqdConfig.PollingTime,
		PollingTemplate: a.cfg.VqdConfig.PollingTemplate,
	}, nil
}

func (a VqdTaskAPI) delVqdPolling(c *gin.Context, _ *struct{}) (any, error) {
	ID, _ := strconv.Atoi(c.Param("id"))
	task, err := a.core.DelVqdPolling(c.Request.Context(), ID)
	if err != nil {
		return nil, reason.ErrServer.SetMsg(fmt.Sprintf(`del vqd polling [%d] err [%s]`, ID, err.Error()))
	}
	errs := a.vqdSdkCore.DelPollingTask(task.ChannelID)
	if errs != nil {
		slog.Error(fmt.Sprintf(`del vqd polling task err [%s]`, err.Error()))
	}
	return gin.H{"data": "OK!"}, err
}

func (a VqdTaskAPI) delVqdPollingAll(c *gin.Context, in *vqd.DelVqdPollingInput) (any, error) {
	if len(in.IDs) == 0 {
		return nil, reason.ErrServer.SetMsg(fmt.Sprintf(`del vqdcms ids is empty`))
	}
	_, err := a.core.DelVqdPollingAll(c.Request.Context(), in.IDs)
	if err != nil {
		return nil, reason.ErrServer.SetMsg(fmt.Sprintf(`del vqd polling [%v] err [%s]`, in.IDs, err.Error()))
	}
	for _, v := range in.IDs {
		errs := a.vqdSdkCore.DelPollingTask(v)
		if errs != nil {
			slog.Error(fmt.Sprintf(`del all vqd polling task err [%s]`, errs.Error()))
		}
	}
	return gin.H{"data": "OK!"}, err
}
