package controller

/*
#include <uvdbus/smart_sound.h>
*/
import "C"
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"
)

var (
	airPlayParams player.AirPlayParams
	airPlayerFifo player.AirPlayFifo

	hasGetAirPlayParams bool = false
	hasGetAirPlayFifo   bool = false

	airplayFirstPlay bool = true // airplay投射过来，第一次收到play指令

	volBack int = -1
)

const (
	SPlayer_PLAYERPAUSE_EVT_PAUSE int = iota
	SPlayer_PLAYERPAUSE_EVT_PLAY
)

func AirPlayerMsgProcess2(cmdid uint32, msg string) {
	if !*log.TerminalCmd {
		log.Println(log.DebugLog, "AirPlayerMsgProcess2 airplay cmd:", cmdid, "  msg:", msg)
	}

	switch cmdid {
	case uint32(C.CMD_SPLAYER_MSG_TYPE_CREATE):
		log.Println(log.WarningLog, "airplay-------------on--------------- CMD_SPLAYER_MSG_TYPE_CREATE")

		CurMusicSrcOnOffSt.AirPlayOn = true

	case uint32(C.CMD_SPLAYER_MSG_TYPE_DEL):
		log.Println(log.WarningLog, "airplay--------------off-------------- CMD_SPLAYER_MSG_TYPE_DEL")

		player.ChangeAirPlayOnLineSt(false)

		CurMusicSrcOnOffSt.AirPlayOn = false

		volBackInit()
	case uint32(C.CMD_SPLAYER_MSG_TYPE_STREAM_NTF):

	case uint32(C.CMD_SPALYER_MSG_TYPE_START):

	case uint32(C.CMD_SPLAYER_MSG_TYPE_STOP):
		log.Println(log.WarningLog, "airplay---------------------------- CMD_SPLAYER_MSG_TYPE_STOP")

		if player.PlayerHander[PlayerType_Airplay].IsInterrupt() {
			log.Println(log.WarningLog, "airplay has been interrput,ignore.")
			return
		}

		if GetCurPlayerId() != PlayerType_Airplay {
			log.Printf(log.WarningLog, "cutplayer is not airplay, curId:%+v\n", GetCurPlayerId())
			return
		}

		player.ChangeAirPlayOnLineSt(false)

		player.SoundEffectPlayCmd(CMD_SE_PLAY, SoundNotice_Stuichufankui001.GetPath())

		eventPoint.DeviceDisconEvent(eventPoint.ModelValAirplay)
		airplayFirstPlay = true
		volBackInit()
	case uint32(C.CMD_SPLAYER_MSG_TYPE_SET_VOLUME):
		if len(msg) < 1 {
			log.Println(log.WarningLog, "param nil")
			return
		}
		var tmp struct {
			VolPer int `json:"volume"`
		}
		if err := json.Unmarshal([]byte(msg), &tmp); nil == err {
			if GetCurPlayerId() != PlayerType_Airplay {
				log.Printf(log.WarningLog, "cur player is not airplay(playerId:%d)\n", GetCurPlayerId())
				volBack = tmp.VolPer
				return
			}
			player.ProjectorVolProcess(tmp.VolPer)
		} else {
			log.Println(log.ErrorLog, err.Error())
			return
		}
	case uint32(C.CMD_SPLAYER_MSG_TYPE_STREAM_PLAYPAUSE):
		var tmp struct {
			Val    int `json:"playEvt"`
			VolPer int `json:"volume"`
		}
		err := json.Unmarshal([]byte(msg), &tmp)
		if nil != err {
			log.Println(log.ErrorLog, err.Error())
			return
		}
		switch tmp.Val {
		case SPlayer_PLAYERPAUSE_EVT_PLAY:
			log.Printf(log.WarningLog, "airplay---------------------------- SPlayer_PLAYERPAUSE_EVT_PLAY:%+v\n", msg)

			/*if player.PlayerHander[PlayerType_Airplay].IsInterrupt() {
				log.Println(log.WarningLog, "airplay has been interrput,ignore.")
				player.AirPlayPauseForIgnoreCmd()
				return
			}*/

			if GetCurPlayerId() != PlayerType_Airplay {
				player.SoundEffectPlayCmd(CMD_SE_PLAY, SoundNotice_Slianjiechenggong001.GetPath())
				IconLed_IconLianjie003.Show()
			}

			player.ChangeAirPlayOnLineSt(true)

			if airplayFirstPlay {
				airplayFirstPlay = false
				if tmp.VolPer >= 0 {
					log.Println(log.DebugLog, "volume of play params:", tmp.VolPer)
					if -1 != volBack && 0 == tmp.VolPer {
						tmp.VolPer = volBack
						volBackInit()
						log.Println(log.WarningLog, "volume of play params change to volBack:", tmp.VolPer)
					}
					player.ProjectorVolProcess(tmp.VolPer)
				}
			}

			eventPoint.DeviceConEvent(eventPoint.ModelValAirplay)
		case SPlayer_PLAYERPAUSE_EVT_PAUSE:
			log.Println(log.WarningLog, "airplay---------------------------- SPlayer_PLAYERPAUSE_EVT_PAUSE")

			/*if player.PlayerHander[PlayerType_Airplay].IsInterrupt() {
				log.Println(log.WarningLog, "airplay has been interrput,ignore.")
				return
			}*/

			if player.PlayerHander[PlayerType_Airplay].IsPlaying() {
				player.AirplayPlayStateSet(false)
				player.MonitorAirplayPlayerBroadcast(MUSIC_ST_PAUSED)
			} else {
				log.Println(log.DebugLog, "airplay player is not playing, ignore pause.")
			}

			eventPoint.DeviceDisconEvent(eventPoint.ModelValAirplay)
		default:
			log.Println(log.ErrorLog, "invalid val")
		}
	}
}

func AirPlayerMsgProcess(cmdid uint32, msg string) {
	if !*log.TerminalCmd {
		log.Println(log.DebugLog, "AirPlayerMsgProcess airplay cmd:", cmdid, "  msg:", msg)
	}

	switch cmdid {
	case uint32(C.CMD_SPLAYER_MSG_TYPE_CREATE):
		log.Println(log.WarningLog, "airplay-------------on--------------- CMD_SPLAYER_MSG_TYPE_CREATE")

		player.GetSystemVolPer()
		err := json.Unmarshal([]byte(msg), &airPlayerFifo)
		if nil != err {
			log.Println(log.DebugLog, err.Error())
			return
		}
		hasGetAirPlayFifo = true
		CurMusicSrcOnOffSt.AirPlayOn = true

	case uint32(C.CMD_SPLAYER_MSG_TYPE_DEL):
		log.Println(log.WarningLog, "airplay--------------off-------------- CMD_SPLAYER_MSG_TYPE_DEL")

		if hasGetAirPlayFifo {
			hasGetAirPlayFifo = false
		}
		airplayStop(false)
		CurMusicSrcOnOffSt.AirPlayOn = false

		volBackInit()
	case uint32(C.CMD_SPLAYER_MSG_TYPE_STREAM_NTF):
		//log.Println(log.WarningLog, "airplay---------------------------- CMD_SPLAYER_MSG_TYPE_STREAM_NTF")

		err := json.Unmarshal([]byte(msg), &airPlayParams)
		if nil != err {
			log.Println(log.DebugLog, err.Error())
			return
		}
		hasGetAirPlayParams = true
	case uint32(C.CMD_SPALYER_MSG_TYPE_START):
		//log.Println(log.WarningLog, "airplay---------------------------- CMD_SPLAYER_MSG_TYPE_START")
		//if player.PlayerHander[PlayerType_Airplay].IsInterrupt() {
		//	log.Println(log.WarningLog, "airplay has been interrput,igonre.")
		//	player.AirPlayPauseForIgonreCmd()
		//	return
		//}
		//if hasGetAirPlayParams && hasGetAirPlayFifo {
		//	//hasGetAirPlayParams = false
		//	//hasGetAirPlayFifo = false
		//
		//	if GetCurPlayerId() != PlayerType_Airplay {
		//		player.SoundEffectPlayCmd(CMD_SE_PLAY, SoundNotice_Slianjiechenggong001.GetPath())
		//		IconLed_IconLianjie003.Show()
		//	}
		//
		//	var tmp player.AirParams2Play
		//	tmp.AirPlayFifo = airPlayerFifo
		//	tmp.AirPlayParams = airPlayParams
		//
		//	if SetPlayerArgs(PlayerType_Airplay, tmp) {
		//		log.Printf(log.DebugLog, "airplay arg:%+v", tmp)
		//		hasSetUrl = true
		//	}
		//	player.PlayerHander[PlayerType_Airplay].RequestPlay_Async()
		//} else {
		//	log.Println(log.WarningLog, "hasGetAirPlayParams:", hasGetAirPlayParams,
		//		"  hasGetAirPlayFifo:", hasGetAirPlayFifo)
		//	return
		//}
		//player.AirPlayStartTrig()
		//
		//eventPoint.DeviceConEvent(eventPoint.ModelValAirplay)
	case uint32(C.CMD_SPLAYER_MSG_TYPE_STOP):
		log.Println(log.WarningLog, "airplay---------------------------- CMD_SPLAYER_MSG_TYPE_STOP")

		if player.PlayerHander[PlayerType_Airplay].IsInterrupt() {
			log.Println(log.WarningLog, "airplay has been interrput,ignore.")
			return
		}
		airplayStop(false)

		player.SoundEffectPlayCmd(CMD_SE_PLAY, SoundNotice_Stuichufankui001.GetPath())

		eventPoint.DeviceDisconEvent(eventPoint.ModelValAirplay)
		volBackInit()
		airplayFirstPlay = true
	case uint32(C.CMD_SPLAYER_MSG_TYPE_SET_VOLUME):
		if len(msg) < 1 {
			log.Println(log.WarningLog, "param nil")
			return
		}
		var tmp struct {
			VolPer int `json:"volume"`
		}
		if err := json.Unmarshal([]byte(msg), &tmp); nil == err {
			if GetCurPlayerId() != PlayerType_Airplay {
				log.Printf(log.WarningLog, "cur player is not airplay(playerId:%d)\n", GetCurPlayerId())
				volBack = tmp.VolPer
				return
			}
			//player.VolChangeByPercent(tmp.VolPer)
			// prd reverse : 20180322
			player.ProjectorVolProcess(tmp.VolPer)
		} else {
			log.Println(log.ErrorLog, err.Error())
			return
		}
	case uint32(C.CMD_SPLAYER_MSG_TYPE_STREAM_PLAYPAUSE):
		var tmp struct {
			Val    int `json:"playEvt"`
			VolPer int `json:"volume"`
		}
		err := json.Unmarshal([]byte(msg), &tmp)
		if nil != err {
			log.Println(log.ErrorLog, err.Error())
			return
		}
		switch tmp.Val {
		case SPlayer_PLAYERPAUSE_EVT_PLAY:
			log.Printf(log.WarningLog, "airplay---------------------------- SPlayer_PLAYERPAUSE_EVT_PLAY:%+v\n", msg)

			if player.PlayerHander[PlayerType_Airplay].IsInterrupt() {
				log.Println(log.WarningLog, "airplay has been interrput,ignore.")
				player.AirPlayPauseForIgnoreCmd()
				return
			}
			//player.AirPlayPauseDoneSet(false)

			if hasGetAirPlayParams && hasGetAirPlayFifo {

				if GetCurPlayerId() != PlayerType_Airplay {
					player.SoundEffectPlayCmd(CMD_SE_PLAY, SoundNotice_Slianjiechenggong001.GetPath())
					IconLed_IconLianjie003.Show()
				}

				var tmp player.AirParams2Play
				tmp.AirPlayFifo = airPlayerFifo
				tmp.AirPlayParams = airPlayParams

				if SetPlayerArgs(PlayerType_Airplay, tmp) {
					log.Printf(log.DebugLog, "airplay arg:%+v\n", tmp)
					hasSetUrl = true
				}
				//player.AirPlayPlayDoneSet(true)
				player.PlayerHander[PlayerType_Airplay].RequestPlay_Async(nil)
			} else {
				log.Println(log.WarningLog, "hasGetAirPlayParams:", hasGetAirPlayParams,
					"  hasGetAirPlayFifo:", hasGetAirPlayFifo)
				return
			}
			player.AirPlayStartTrig()

			if airplayFirstPlay {
				airplayFirstPlay = false
				if tmp.VolPer >= 0 {
					log.Println(log.DebugLog, "volume of play params:", tmp.VolPer)
					if -1 != volBack && 0 == tmp.VolPer {
						tmp.VolPer = volBack
						volBackInit()
						log.Println(log.WarningLog, "volume of play params change to volBack:", tmp.VolPer)
					}
					player.ProjectorVolProcess(tmp.VolPer)
				}
			}

			eventPoint.DeviceConEvent(eventPoint.ModelValAirplay)
		case SPlayer_PLAYERPAUSE_EVT_PAUSE:
			log.Println(log.WarningLog, "airplay---------------------------- SPlayer_PLAYERPAUSE_EVT_PAUSE")

			if player.PlayerHander[PlayerType_Airplay].IsInterrupt() {
				log.Println(log.WarningLog, "airplay has been interrput,ignore.")
				return
			}

			if player.PlayerHander[PlayerType_Airplay].IsPlaying() {
				// prd reverse : 20180328
				//player.SoundEffectPlayCmd(CMD_SE_PLAY, SoundNotice_Slianjiechenggong001.GetPath())
				//player.AirPlayPauseDoneSet(true)

				SendSCmd(SCMD_MusicPlayer_Pause, PlayerArg{GloablePause: false, NotShowIcon: true})
			} else {
				log.Println(log.DebugLog, "airplay player is not playing, ignore pause.")
			}

			eventPoint.DeviceDisconEvent(eventPoint.ModelValAirplay)
		default:
			log.Println(log.ErrorLog, "invalid val")
		}
	}
}

func airplayStop(globalPause bool) {
	if player.PlayerHander[PlayerType_Airplay].IsActive() {
		player.AirPlayStopTrig(globalPause)
	}
}

func volBackInit() {
	volBack = -1
}
