package routes

import (
	"context"
	"game-driver/internal/common"
	"game-driver/internal/middleware"
	"game-driver/internal/routes/standby"
	"game-driver/internal/routes/standby_ctrl"
	"game-driver/internal/schema"
	"game-driver/leaf"
	"github.com/go-pkgz/cronrange"
	"go.uber.org/zap"
	"sync"
)

func WaitAction(ctrl *common.CtrlWait) leaf.HandlerFunc {
	ps := common.NewPauseSub(ctrl)

	return func(c *leaf.Context) {
		payload := leaf.Value[*schema.WaitModel](c, middleware.PayloadJSONKey)

		// 设定默认时间规则,ctrl
		if payload.Cron == "" {
			payload.Cron = "* * * *"
		}

		rules, err := cronrange.Parse(payload.Cron)
		if err != nil {
			zap.S().Errorln("解析时间规则异常: ", err)
			return
		}

		// 等待组
		var waitGroup sync.WaitGroup
		defer waitGroup.Wait()

		// 开启暂停监听
		waitGroup.Add(1)
		go func() {
			defer waitGroup.Done()
			ps.Run(c)
		}()

		// 处理每个待机控制
		handleItem := func(title string, item schema.WaitItemModel, f func(c context.Context) error) {
			waitGroup.Add(1)
			go func() {
				defer waitGroup.Done()
				if f == nil {
					return
				}
				f = standby_ctrl.Time(rules, item.Cron, f)
				if f == nil {
					return
				}
				f = standby_ctrl.Pause(ps, item.Pause, f)
				if f == nil {
					return
				}
				e := f(c)
				if e != nil {
					zap.S().Errorf("%s异常: %s\n", title, e)
				}
			}()
		}

		for _, item := range payload.Items {
			switch item.Type {
			case schema.WaitAudio:
				handleItem("音乐待机控制", item, standby.Audio(item))
			case schema.WaitTTS:
				handleItem("TTS待机控制", item, standby.TTS(item))
			case schema.WaitRelay:
				handleItem("继电器待机控制", item, standby.Relay(item))
			case schema.WaitVideo:
				handleItem("视频待机控制", item, standby.Video(item))
			case schema.WaitWeb:
				handleItem("视频待机控制", item, standby.Web(item))
			case schema.WaitPJLink:
				handleItem("视频待机控制", item, standby.PJLink(item))
			default:
				zap.S().Infof("不支持的类型: %d\n", item.Type)
			}
		}
	}
}
