package controller

import (
	"encoding/json"
	. "netease_control_center/globals"
	"netease_control_center/interfaces/eventPoint"
	"netease_control_center/interfaces/log"
	. "netease_control_center/interfaces/schedule"
	. "netease_control_center/interfaces/vui"
	"netease_control_center/modules/player"
	"strconv"
)

var (
	hasSetUrl  bool = false
	hasPostUrl bool = false
)

func DlnaContinuePlayResultCb(cb SCmdStructExecCb) {
	if cb.Result != SCmdExecStatus_Success {
		player.SetDlnaPlayPauseState(false)
		player.CtrlDlnaCmdToPhone(player.CTRL_DLNA_PAUSE)
		log.Println(log.WarningLog, "cannot play ok. so ctrl dlna pause.")
	} else {
		log.Println(log.WarningLog, "dlna play ok. ")
		player.SetDlnaPlayPauseState(true)
		player.BtDiscon() //add by lupeng 20180824 #PV1-4011
	}
}
func DlnaCmdProcess(cmdid uint32, msg string) {
	if !*log.TerminalCmd {
		log.Printf(log.DebugLog, "dlna cmd:0x%x %+v\n", cmdid, msg)
	}

	switch cmdid {
	case CMD_KPLAYER_CTR_PLAY:
		log.Println(log.WarningLog, "DLNA---------------------------- CMD_KPLAYER_CTR_PLAY")
		if hasSetUrl {
			player.StopDlnaWaitNextTimer()

			player.DlnaStartTrig()

			eventPoint.DeviceConEvent(eventPoint.ModelValDlna)

			if !hasPostUrl {
				if !player.PlayerHander[PlayerType_Dlna].IsPlayerChange(false) {
					if GetCurPlayerId() != PlayerType_Dlna {
						log.Printf(log.WarningLog, "cur player is not dlna(playerId:%d)\n", GetCurPlayerId())
						goto forceIn
					}
					eventPoint.SetEpOsSouce("F141", eventPoint.EpOs_App)
					//SendSCmd(SCMD_MusicPlayer_Play, nil)
					SendSCmdStruct(SCmdStruct{ExecCb: DlnaContinuePlayResultCb, SCmd: SCMD_MusicPlayer_Play})
					return
				}
				log.Println(log.WarningLog, "GetCurPlayerId():", GetCurPlayerId(),
					"PlayerType_Dlna.IsActive():", player.PlayerHander[PlayerType_Dlna].IsActive(), "playPauseState: ", player.GetDlnaPlayPauseState())

				if GetCurPlayerId() == PlayerType_Dlna && player.PlayerHander[PlayerType_Dlna].IsActive() {
					if !player.GetDlnaPlayPauseState() {
						//SendSCmd(SCMD_MusicPlayer_Play, nil)
						player.SetDlnaPlayPauseState(true)
						SendSCmdStruct(SCmdStruct{ExecCb: DlnaContinuePlayResultCb, SCmd: SCMD_MusicPlayer_Play})
					}
					return
				}
			}
		forceIn:
			hasPostUrl = false
			if GetCurPlayerId() != PlayerType_Dlna {
				// prd reverse : 20180322
				//player.SoundEffectPlayCmd(CMD_SE_PLAY, SoundNotice_Slianjiechenggong001.GetPath())
				IconLed_IconLianjie002.Show()
			}
			player.PlayerHander[PlayerType_Dlna].RequestPlay_Async_WithCb(nil, DlnaContinuePlayResultCb)
			player.SetDlnaPlayPauseState(true)
		}
	case CMD_KPLAYER_CTR_PAUSE:
		log.Println(log.WarningLog, "DLNA---------------------------- CMD_KPLAYER_CTR_PAUSE")
		if GetCurPlayerId() != PlayerType_Dlna {
			log.Printf(log.DebugLog, "cur player is not dlna(playerId:)\n", GetCurPlayerId())
			return
		}

		player.SetDlnaPlayPauseState(false)
		if player.PlayerHander[PlayerType_Dlna].IsPlaying() {
			// prd reverse : 20180328
			//player.SoundEffectPlayCmd(CMD_SE_PLAY, SoundNotice_Slianjiechenggong001.GetPath())
			//player.SetDlnaPausePhone(true)
			player.DlnaPlaySeek = true
			eventPoint.SetEpOsSouce("F141", eventPoint.EpOs_App)
			SendSCmd(SCMD_MusicPlayer_Pause, PlayerArg{GloablePause: false, NotShowIcon: true}) // 不显示icon
		} else {
			log.Println(log.DebugLog, "dlna player is not playing, ignore pause.")
		}
	case CMD_KPLAYER_CTR_STOP:
		log.Println(log.WarningLog, "DLNA---------------------------- CMD_KPLAYER_CTR_STOP")
		if GetCurPlayerId() != PlayerType_Dlna {
			log.Printf(log.DebugLog, "cur player is not dlna(playerId:)\n", GetCurPlayerId())
			return
		}
		log.Println(log.WarningLog, "recive stop cmd from phone")
		SendSCmd(SCMD_MusicPlayer_Stop)
		dlnaTrigStop()
		player.DlnaPlaySeek = false
		player.ClearProjectorVolProcess()
		player.SetDlnaPlayPauseState(false)
		// prd reverse : 20180322
		//player.SoundEffectPlayCmd(CMD_SE_PLAY, SoundNotice_Slianjiechenggong001.GetPath())
		eventPoint.DeviceDisconEvent(eventPoint.ModelValDlna)
	case CMD_KPLAYER_CTR_SEEK:
		if GetCurPlayerId() != PlayerType_Dlna {
			log.Printf(log.DebugLog, "cur player is not dlna(playerId:)\n", GetCurPlayerId())
			return
		}

		var seek struct {
			Seektime uint32 `json:"time"` // s
		}
		err := json.Unmarshal([]byte(msg), &seek)
		if nil != err {
			log.Println(log.DebugLog, err)
			return
		}
		SendSCmd(SCMD_MusicPlayer_Seek, seek.Seektime)
	case CMD_KPLAYER_CTR_SET_URL:
		if SetPlayerArgs(PlayerType_Dlna, &msg) {
			hasSetUrl = true
			hasPostUrl = true
		}
		player.DlnaPlaySeek = false
	case CMD_KPLAYER_CTR_CTREATED:
		player.GetSystemVolPer()
		log.Println(log.DebugLog, "dlna has on")
		CurMusicSrcOnOffSt.DlnaOn = true
		player.DlnaPlaySeek = false
		player.SetDlnaPlayPauseState(false)
	case CMD_KPLAYER_CTR_DELTED:
		hasSetUrl = false
		dlnaTrigStop()
		log.Println(log.WarningLog, "dlna has off")
		CurMusicSrcOnOffSt.DlnaOn = false
		player.ClearProjectorVolProcess()
		player.SetDlnaPlayPauseState(false)
		player.DlnaPlaySeek = false
	case CMD_KPLAYER_CTR_SET_VOLUME:
		log.Println(log.WarningLog, "DLNA---------------------------- CMD_KPLAYER_CTR_SET_VOLUME")
		if GetCurPlayerId() != PlayerType_Dlna {
			log.Printf(log.WarningLog, "cur player is not dlna(playerId:)\n", GetCurPlayerId())
			return
		}

		if len(msg) < 1 {
			log.Println(log.WarningLog, "param nil")
			return
		}
		var tmp struct {
			VolPer string `json:"volume"`
		}
		if err := json.Unmarshal([]byte(msg), &tmp); nil == err {
			if volPerDlna, err := strconv.Atoi(tmp.VolPer); nil == err {
				//player.VolChangeByPercent(volPerDlna)
				// prd reverse : 20180322
				player.ProjectorVolProcess(volPerDlna)
			} else {
				log.Println(log.ErrorLog, err.Error())
				return
			}
		} else {
			log.Println(log.WarningLog, err.Error())
			return
		}

	default:

	}

}

func dlnaTrigStop() {
	if player.PlayerHander[PlayerType_Dlna].IsActive() {
		player.DlnaStopTrig()
	}
}
