package controller

/*
#include <uvdbus/smart_sound.h>
*/
import "C"
import (
	"encoding/json"
	"netease_control_center/globals"
	"netease_control_center/interfaces"
	"netease_control_center/interfaces/log"
)

var (
	lastSt              string = "" //保存最后一次的状态，排除pos和timestamp字段
	lastPos             uint32 = 0  //保存最后一次的pos值
	OnlyPosDiffPrintCnt uint32 = 0  //只有pos不同的时候，计数
)

//打印只有pos不同时候计数值，超过次数就打印一次
const OnlyPosDiffMaxCnt = 10

func BroadcastStatus(st globals.VboxBroadcastSt) {
	defer func() {
		globals.BroadcastStTimer.Reset(globals.BRAODCAST_ST_PERIOD)

		if err := recover(); err != nil {
			log.Println(log.ErrorLog, err)
		}
	}()

	boxData, err := json.Marshal(st)
	if err != nil {
		log.Println(log.WarningLog, err.Error())
		return
	}
	if !*log.TerminalCmd {
		tmpPos := st.PlayerStPtr.CurPlayingPos //记录当前的进度值
		tmpTimeStamp := st.TimeStamp
		st.TimeStamp = 0
		st.PlayerStPtr.CurPlayingPos = 0
		tmpSt, e := json.Marshal(st) //去掉timestamp和pos后序列化
		//resume pos and timestamp
		st.PlayerStPtr.CurPlayingPos = tmpPos
		st.TimeStamp = tmpTimeStamp
		if e == nil {
			if lastSt == string(tmpSt) {
				if tmpPos != lastPos {
					//只有pos字段不同
					lastPos = tmpPos
					//log.Println(log.ErrorLog, "OnlyPosDiff st: ", OnlyPosDiffPrintCnt)
					if OnlyPosDiffPrintCnt == 0 {
						log.Printf(log.WarningLog, "- broad vboxSt:%+v\n", string(boxData))
					}
					OnlyPosDiffPrintCnt++

					if OnlyPosDiffPrintCnt >= OnlyPosDiffMaxCnt {
						OnlyPosDiffPrintCnt = 0
					}
				} else {
					//和上次打印全部相同
					OnlyPosDiffPrintCnt = 0
					//log.Println(log.ErrorLog, "some st")
				}
			} else {
				// 和上次打印都不同（大部分不同或者是核心字段不同即认为都不同）
				lastPos = tmpPos
				lastSt = string(tmpSt)
				OnlyPosDiffPrintCnt = 0
				//log.Println(log.ErrorLog, "allDiff st")
				log.Printf(log.WarningLog, "broad vboxSt:%+v\n", string(boxData))
			}
		} else {
			OnlyPosDiffPrintCnt = 0
			log.Printf(log.WarningLog, "e-broad vboxSt:%+v\n", string(boxData))
		}
	}

	interfaces.BroadSignalAll(globals.MODULE_CONTROLLER, uint32(C.CMD_CONTROLLER_RSPMSG_PLAYERSTATUS),
		string(boxData))
}
