package middleware

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

// EmergencyStop 紧急停止中间件
func EmergencyStop(stopper common.Stopper) leaf.HandlerFunc {
	return func(c *leaf.Context) {
		cancel := leaf.WithCancel(c)
		defer stopper.Reset()

		zap.S().Infoln("监听停止信号")
		defer zap.S().Infoln("结束停止信号监听")

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

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

		wait.Add(1)
		go func() {
			defer wait.Done()

			select {
			case <-a:
			case <-stopper.Done():
				{
					zap.S().Infoln("停止信号触发")
					cancel()
					leaf.WithValue[leaf.EndType](c, leaf.EndKey, leaf.EndStop)
				}
			}
		}()

		c.Next()
	}
}
