package standby

import (
	"context"
	"fmt"
	"game-driver/config/wait"
	"game-driver/internal/schema"
	"game-driver/pkg/pjlink"
	"go.uber.org/zap"
	"time"
)

func PJLink(_ schema.WaitItemModel) func(c context.Context) error {
	return func(c context.Context) error {
		cfg := (wait.C).(wait.PJLink)
		pjc := pjlink.NewClient(cfg.Ip, cfg.Port, cfg.Password, cfg.Id)

		zap.S().Infoln("打开待机投影仪")
		resp, err := pjc.PowerOnSync()
		if err != nil {
			return fmt.Errorf("打开投影仪异常: %w", err)
		}
		zap.S().Infoln("打开投影仪结果：", resp)

		run := true
		for run {
			select {
			case <-c.Done():
				zap.S().Infoln("关闭待机投影仪")
				resp, err = pjc.PowerOffSync()
				if err != nil {
					return fmt.Errorf("关闭投影仪异常: %w", err)
				}
				zap.S().Infoln("关闭投影仪结果：", resp)
				run = false
				break
			case <-time.After(time.Minute * 30):
				zap.S().Infoln("轮询待机投影仪")
				resp, err = pjc.PowerOnSync()
				if err != nil {
					return fmt.Errorf("轮询投影仪异常: %w", err)
				}
				zap.S().Infoln("轮询投影仪结果：", resp)
			}
		}

		return nil
	}
}
