package controller

import (
	. "netease_control_center/globals"
	"netease_control_center/interfaces/eventPoint"
	"netease_control_center/interfaces/log"
	"netease_control_center/interfaces/schedule"
	"netease_control_center/modules/hardware/misc"
	"netease_control_center/nembd/controller/adau1761"
	"netease_control_center/utils/customization"
	"netease_control_center/utils/ntp"
	"time"
)

var (
	logDeamonTimer = time.NewTimer(log.FLUSH_INTERVAL)

	pingticker = time.NewTicker(10 * time.Second)

	recordVolume = time.NewTimer(500 * time.Microsecond)  //lupeng change 3s to 500ms   20180904

	calTimeTicker = time.NewTicker(24 * time.Hour)

	ticker_30min = time.NewTicker(30 * time.Minute)
)

func ResetRecordVolumeTimer() {
	recordVolume.Reset(500 * time.Microsecond) //lupeng change 3s to 500ms   20180904
}

func GetCurVboxBroadcastSt(print bool) VboxBroadcastSt {
	var st VboxBroadcastSt
	var tmpPlayerSt = CurPlayerSt

	st.ScenesStPtr = schedule.GetSceneStatus()
	st.VboxVolStPtr = &CurVboxVolSt
	st.VboxVolStPtr.Action = VOL_NULL_ACTION
	st.CurrentStatus = schedule.GetMusicField()
	st.PlayerStPtr = &tmpPlayerSt
	st.DeviceMode = getCurDeviceMode(print)
	st.ModeId = PlayListSrcRec.ModeId

	st.CurTask = uint8(schedule.GetCurScheduleDomain())

	if st.CurrentStatus == SCENE_FIELD_ST && len(schedule.GetCurScenePlayerDetail().Uuid) == 0 {
		st.PlayerStPtr = nil
	}

	st.TimeStamp = time.Now().Unix()
	st.Type = 0
	st.VboxVolStPtr.VboxIp = VboxIp

	return st
}

func timerFunc() {
	for {
		select {
		case <-calTimeTicker.C:
			go func() {
				s, err := ntp.CalTimeWithDefaultServers()
				log.Println(log.DebugLog, "Cal time with server:", s, " result:", err)
			}()

		case <-logDeamonTimer.C:
			log.LogDaemon()
			logDeamonTimer.Reset(log.FLUSH_INTERVAL)

		case <-pingticker.C:
			SendPing()

		case stTmp := <-BroadcastStChan:
			stTmp.Type = 1
			stTmp.VboxVolStPtr.VboxIp = VboxIp
			stTmp.DeviceMode = getCurDeviceMode(false)
			BroadcastStatus(stTmp)

		case <-BroadcastStTimer.C:
			BroadcastStatus(GetCurVboxBroadcastSt(false))

		case <-recordVolume.C:
			eventPoint.EpRecord("H511", map[string]interface{}{"volume": adau1761.MustGetVol()})
			if getCurDeviceMode(false) == Exec_MusicPlay_mode {
				misc.VolTrigeMicAdc()
				BroadcastStatus(GetCurVboxBroadcastSt(false))   //lupeng add 20180904
			}

		case <-ticker_30min.C:
			go customization.DoCheck(20)
		}
	}
}
