package controller

import (
	"fmt"
	"netease_control_center/globals"
	"netease_control_center/interfaces/log"
	"netease_control_center/utils/cron"
	"time"
)

var (
	cron_system *cron.Cron
)

func CrontabInit() {
	log.Println(log.DebugLog, "Ota night check registe!")
	if cron_system != nil && cron_system.IsRunning() {
		cron_system.Stop()
	}
	cron_system = cron.New()
	//OTA NIGHT CHECK
	if err := cron_system.AddFunc(fmt.Sprintf("0 0 %d * * *", globals.OTA_BEGIN_HOUR), otaEveryNightCheck); err != nil {
		log.Println(log.DebugLog, "Ota night check err:", err)
	}

	if err := cron_system.AddFunc("0 0 0 * * *", Nduilite_fespa_set); err != nil {
		log.Println(log.ErrorLog, "Set Nduilite_fespa_set error 0", err)
	}

	if err := cron_system.AddFunc("0 0 7 * * *", Nduilite_fespa_set); err != nil {
		log.Println(log.ErrorLog, "Set Nduilite_fespa_set error 7", err)
	}

	if err := cron_system.AddFunc("0 0 5 * * *", func() {
		Nduilite_fespa_set_arg(true)
	}); err != nil {
		log.Println(log.ErrorLog, "Set Nduilite_fespa_set_arg with sdk init", err)
	}

	if micControl.MainSwitch == true {
		start := time.Unix(micControl.StartTimeStamp/1000, 0).In(ChinaLocation)
		end := time.Unix(micControl.EndTimeStamp/1000, 0).In(ChinaLocation)
		log.Println(log.DebugLog, "micControl,start:", start, " end:", end)
		if err := cron_system.AddFunc(fmt.Sprintf("0 %d %d * * *", start.Minute(), start.Hour()), micCronStart); err != nil {
			log.Println(log.ErrorLog, "Set mic control start error", err)
		}

		if start.Hour() != end.Hour() || start.Minute() != end.Minute() {
			if err := cron_system.AddFunc(fmt.Sprintf("0 %d %d * * *", end.Minute(), end.Hour()), micCronEnd); err != nil {
				log.Println(log.ErrorLog, "Set mic control end error", err)
			}
		}
	}
}

func UpdateCronTime() {
	log.Println(log.DebugLog, "Update cron time!")
	if cron_system != nil {
		if cron_system.IsRunning() == false {
			cron_system.Start()
		}
		log.Printf(log.DebugLog, "Get cron entries: %+v\n", cron_system.Entries())
	}
}
