package standby_ctrl

import (
	"context"
	"game-driver/internal/common"
	"go.uber.org/zap"
	"sync"
	"time"
)

// Pause 暂停控制器
func Pause(ps *common.PauseSub, isPause bool, play func(c context.Context) error) func(c context.Context) error {
	return func(c context.Context) error {
		var cancel context.CancelFunc
		run := true

		if isPause {
			zap.S().Infoln("待机暂停控制器")
			defer zap.S().Infoln("待机暂停控制器结束")

			p := ps.GetNew()
			defer ps.Close(p)

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

			wait.Add(1)
			go func() {
				defer wait.Done()
				for {
					select {
					case <-c.Done():
						return
					case v := <-p:
						if v == 1 {
							zap.S().Infoln("待机控制器 Pause 触发")
							run = false
							cancel()
						} else {
							zap.S().Infoln("待机控制器 Resume 触发")
							run = true
						}
					}
				}
			}()
		}

		for {
			select {
			case <-c.Done():
				return nil
			default:
				if run {
					nc, cc := context.WithCancel(c)
					cancel = cc
					err := play(nc)
					if err != nil {
						zap.S().Infoln("执行后续操作异常: ", err)
					}
				}
				// 避免忙循环，短暂休眠
				time.Sleep(10 * time.Millisecond)
			}
		}
	}
}
