package api

import (
	"easyvqd/internal/conf"
	"git.lnton.com/lnton/pkg/reason"
	"github.com/gin-gonic/gin"
	"github.com/ixugo/goddd/pkg/web"
	"github.com/jinzhu/copier"
	"github.com/pelletier/go-toml/v2"
	"io"
	"log/slog"
	"strconv"
	"sync"
)

var confMutex sync.Mutex

type ConfigAPI struct {
	cfg *conf.Bootstrap
	uc  *Usecase
}

func registerConfig(g gin.IRouter, api ConfigAPI, handler ...gin.HandlerFunc) {
	group := g.Group("/api/configs", handler...)
	//group.GET("", api.getToml)
	//group.PUT("", api.editToml)

	group.GET("/base", web.WarpH(api.getBase))
	group.PUT("/base", web.WarpH(api.editBase))
	group.GET("/default", web.WarpH(api.getDefaultConfig))

}

type getBaseOutput struct {
	SaveDay int32 `json:"save_day"`
}
type editBaseInput struct {
	SaveDay int32 `json:"save_day"`
}
type getBaseConfigOutput struct {
	FrmNum       int32             `json:"frm_num"`
	IsDeepLearn  bool              `json:"is_deep_learn"`
	VqdLgtDark   conf.VqdLgtDark   `json:"vqd_lgt_dark"`  // 亮度检测
	VqdBlue      conf.VqdBlue      `json:"vqd_blue"`      // 蓝屏检查
	VqdClarity   conf.VqdClarity   `json:"vqd_clarity"`   // 清晰度检查
	VqdShark     conf.VqdShark     `json:"vqd_shark"`     // 抖动检查
	VqdFreeze    conf.VqdFreeze    `json:"vqd_freeze"`    // 冻结检测
	VqdColor     conf.VqdColor     `json:"vqd_color"`     // 偏色检测
	VqdOcclusion conf.VqdOcclusion `json:"vqd_occlusion"` // 遮挡检测
	VqdNoise     conf.VqdNoise     `json:"vqd_noise"`     // 噪声检测
	VqdContrast  conf.VqdContrast  `json:"vqd_contrast"`  // 对比度检测
	VqdMosaic    conf.VqdMosaic    `json:"vqd_mosaic"`    // 马赛克检测
	VqdFlower    conf.VqdFlower    `json:"vqd_flower"`    // 花屏检测
}

func (uc *ConfigAPI) editBase(c *gin.Context, in *editBaseInput) (any, error) {
	uc.cfg.VqdConfig.SaveDay = in.SaveDay
	conf.WriteConfig(uc.cfg, uc.cfg.ConfigDirPath())
	return in, nil
}
func (uc *ConfigAPI) getDefaultConfig(_ *gin.Context, _ *struct{}) (getBaseConfigOutput, error) {
	return getBaseConfigOutput{
		FrmNum:       uc.cfg.VqdConfig.FrmNum,
		IsDeepLearn:  uc.cfg.VqdConfig.IsDeepLearn,
		VqdLgtDark:   uc.cfg.VqdLgtDark,
		VqdBlue:      uc.cfg.VqdBlue,
		VqdClarity:   uc.cfg.VqdClarity,
		VqdShark:     uc.cfg.VqdShark,
		VqdFreeze:    uc.cfg.VqdFreeze,
		VqdColor:     uc.cfg.VqdColor,
		VqdOcclusion: uc.cfg.VqdOcclusion,
		VqdNoise:     uc.cfg.VqdNoise,
		VqdContrast:  uc.cfg.VqdContrast,
		VqdMosaic:    uc.cfg.VqdMosaic,
		VqdFlower:    uc.cfg.VqdFlower,
	}, nil
}
func (uc *ConfigAPI) getBase(_ *gin.Context, _ *struct{}) (getBaseOutput, error) {
	confMutex.Lock()
	defer confMutex.Unlock()

	return getBaseOutput{
		SaveDay: uc.cfg.VqdConfig.SaveDay,
	}, nil
}
func (uc *ConfigAPI) getToml(c *gin.Context) {
	c.Header("Content-Type", "application/toml")
	if err := toml.NewEncoder(c.Writer).Encode(uc.uc.Conf); err != nil {
		slog.Error("获取配置失败", "err", err)
		return
	}
}

func (uc *ConfigAPI) editToml(c *gin.Context) {
	b, err := io.ReadAll(io.LimitReader(c.Request.Body, 1024*20))
	if err != nil {
		web.Fail(c, reason.ErrBadRequest.SetMsg(err.Error()))
		return
	}
	if len(b) <= 10 {
		web.Fail(c, reason.ErrBadRequest.SetMsg("错误的文件"))
		return
	}

	data, err := strconv.Unquote(string(b))
	if err != nil {
		web.Fail(c, reason.ErrBadRequest.SetMsg(err.Error()))
		return
	}

	var cfg conf.Bootstrap
	if err := toml.Unmarshal([]byte(data), &cfg); err != nil {
		web.Fail(c, reason.ErrBadRequest.SetMsg(err.Error()))
		return
	}

	if err := copier.Copy(uc.uc.Conf, cfg); err != nil {
		web.Fail(c, reason.ErrServer.SetMsg(err.Error()))
		return
	}
	if err := conf.WriteConfig(uc.uc.Conf, uc.uc.Conf.ConfigDirPath()); err != nil {
		web.Fail(c, reason.ErrServer.SetMsg(err.Error()))
		return
	}

	web.Success(c, gin.H{"msg": "ok"})
}
