package middleware

import (
	"game-driver/internal/schema"
	"game-driver/leaf"
	"game-driver/pkg/tts"
	"go.uber.org/zap"
	"sync"
	"time"
)

// TickerAction 定时器动作,用于在指定时间点执行打印和语音播报
func TickerAction() leaf.HandlerFunc {
	return func(c *leaf.Context) {
		pm := leaf.Value[*schema.PlayModal](c, PayloadJSONKey)

		// 构建打印和语音播报的时间映射
		printMap := make(map[int]schema.PrintModal, len(pm.Print))
		for _, p := range pm.Print {
			printMap[p.Time] = p
		}
		ttsMap := make(map[int]schema.TTSTimer, len(pm.TTS.Timer))
		for _, t := range pm.TTS.Timer {
			ttsMap[t.Time] = t
		}

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

		// 结束信号通道
		a := make(chan struct{})
		// 发送结束信号
		defer close(a)

		wait.Add(1)
		go func() {
			start := time.Now()
			defer wait.Done()
			// 定时器
			ticker := time.NewTicker(time.Second)
			defer ticker.Stop()

			zap.S().Infoln("开始 Ticker 计时")
			defer zap.S().Infoln("结束 Ticker 计时")

			for over := false; !over; {
				select {
				case <-a:
					over = true
				case m := <-ticker.C:
					{
						s := int(m.Sub(start).Seconds())
						if _, ok := printMap[s]; ok {
							//TODO: 屏幕打印
						}
						if to, ok := ttsMap[s]; ok {
							tts.DefaultTTS.Sound(to.Value)
						}
					}
				}
			}
		}()
		c.Next()
	}
}
