package player

import (
	"fmt"
	. "netease_control_center/globals"
	"netease_control_center/interfaces/http"
	"netease_control_center/interfaces/log"
	. "netease_control_center/interfaces/schedule"
	"netease_control_center/modules/hardware/mcu_leds/atservice"
	"time"
	"netease_control_center/interfaces/vui"
)

const (
	WIFI_PLAYER_NAME = "wifi_player"
	WIFI_SET_ARG_LEN = 1
)

var (
	wifiNeedSeekToPos bool = false // 在重新拉取url播放的情况下，需要在播放回调的时候，seek到指定位置
	wifiSeekPos       uint32

	wifiArgHasSet bool = false
	wifiPlayArg   interface{}

	// 音乐播放状态变化时，需要更新
	wifiPlayerSt = PlayerStatus{PlayerSrc: WIFI_SRC, MusicId: nil, MusicListId: nil, ContinuousTaskSt: MUSIC_ST_IDLE, CurPlayingPos: 0,
		TaskField:    FIELD_NULL,
		SingleTaskSt: AUDIO_ST_IDLE}
)

func WifiPause() {
	wifiPauseApi()
}

func toastNetworkError(isJustPlayEror bool) {
	tmpconfig := GetDefaultNoticePlayerParams()
	tmpconfig.Keep = false
	tmpconfig.NeedRepeat = true
	tmpconfig.Level = TTS_LEVEL_1
	tmpconfig.SrcType = AdSrcType_FILE
	tmpconfig.Tts = vui.SoundNotice_Alianwang010.GetPath()
	tmpconfig.LedOn = DirectLed{EffectId: atservice.GUIDE_EFFECT_ID_SYSTEM_ERR, Action: atservice.GUIDE_ACTION_START}
	tmpconfig.LedOff = DirectLed{EffectId: atservice.GUIDE_EFFECT_ID_SYSTEM_ERR, Action: atservice.GUIDE_ACTION_STOP}
	if isJustPlayEror == false {
		tmpconfig.BeforeExecFunc = func() {
			SoundEffectPlayCmd(CMD_SE_PLAY, vui.SoundNotice_Slianwangshibai001.GetPath())
			time.Sleep(800 * time.Millisecond)
		}
	}
	NoticePlayerSendSCmd2(SCMD_SuperTask_Tts_Ctrl_Play, tmpconfig)
}

func WifiPlay(start int, arg SCmd_Args) bool {
	if !isNetConnect() {
		log.Println(log.ErrorLog, "WifiPlay: internet is down")
		return false
	} else {
		log.Printf(log.DebugLog, "start:%+v arg:%+v\n", start, arg)
	}

	if REQUEST_PLAY_PARAMS == start {
		ttsNoMusic = false
		if wifiArgHasSet {
			if nil != arg.OemArg {
				if argv, ok := arg.OemArg.(SCmd_Args); ok {
					wifiNeedSeekToPos = true
					wifiSeekPos = uint32(argv.StartPos)
				}
			}

			wifiArgHasSet = false
			return wifiPlayApi(wifiPlayArg)
		} else {
			log.Println(log.ErrorLog, "wifiArgHasSet: false")
			return false
		}
	} else {
		// 如果不是request,检查播放列表是否为空,为空拉去私人FM播放
		if LocalMusicList[CUR_MUSIC_LIST].IsNil() {
			var musicAction, musicActionSrc string = "", ""
			switch eVal := wifiPlayArg.(type) {
			case *ServerMusicList:
				musicAction = eVal.Action
				musicActionSrc = eVal.ActionSrc
			case *ServerMusicLists:
				musicAction = eVal.Action
				musicActionSrc = eVal.ActionSrc
			default:
				log.Println(log.WarningLog, "err play type")
			}

			serverListParams := http.MusicListServerType{
				Src:     SERVER_RCMD,
				Id:      nil,
				Params:  nil,
				Start:   0,
				Size:    PAGE_SIZE,
				WantTts: true,

				Mode: CurPlayingMode,
			}
			list, err := GetMusicListNew(PlayerType_Wifi, true, serverListParams)
			if nil != err {
				//NoticePlayerSendSCmd(SCMD_SuperTask_Tts_Play, MusicErrTtsMap[string(SERVER_RCMD)], CONST_AUDIO_ID, AdSrcType_TTS,
				//	TTS_LEVEL_1, true, false)
				mscToastTts(MusicErrTtsMap[string(SERVER_RCMD)], CONST_AUDIO_ID, true, false, nil)
				log.Println(log.ErrorLog, err.Error())

				status := PlayerHander[PlayerType_Wifi].GetPlayerStatus()
				status.Status = MUSIC_ST_PAUSED
				PlayerHander[PlayerType_Wifi].SetPlayerStatus(status)
			} else {
				list.Action = musicAction
				list.ActionSrc = musicActionSrc
				list.InnerTts = list.PullTts
				list.InnerTtsUrl = list.PullTtsUrl
				wifiPlayApi(list)
			}
		} else {
			// 下面2种情况,都是歌曲id未变,切换行为也未变,因此延续用之前的

			isChange := PlayerHander[PlayerType_Wifi].IsPlayerChange(true)
			log.Printf(log.DebugLog, "\nstatus:%+v, isPlayerChange:%+v\n",
				PlayerHander[PlayerType_Wifi].GetPlayerStatus(),
				isChange)
			if isChange {
				// 拉取url重新播放
				songId := PlayerHander[PlayerType_Wifi].GetPlayerStatus().Uuid
				if "" == songId && nil != LocalMusicList[GetMusicListIndex()].GetCurPos() {
					songId = LocalMusicList[GetMusicListIndex()].GetCurPos().Value.(*SongInfo).Id
				}
				songInfo := SongInfo{Id: songId, Duration: PlayerHander[PlayerType_Wifi].GetPlayerStatus().Duration}
				wifiPlayApi(&songInfo)
				if PLAY_FROM_START_POS != start {
					// 收到play的消息后， 需要seek到指定位置
					wifiNeedSeekToPos = true
					wifiSeekPos = uint32(start)
				}
			} else {
				if PLAY_FROM_START_POS == start {
					// 拉去url重新播放
					songId := PlayerHander[PlayerType_Wifi].GetPlayerStatus().Uuid
					if "" == songId && nil != LocalMusicList[GetMusicListIndex()].GetCurPos() {
						songId = LocalMusicList[GetMusicListIndex()].GetCurPos().Value.(*SongInfo).Id
					}
					songInfo := SongInfo{Id: songId, Duration: PlayerHander[PlayerType_Wifi].GetPlayerStatus().Duration}
					wifiPlayApi(&songInfo)
				} else {
					// 直接发送播放命令
					wifiPlayApi(nil)
				}
			}
		}

		return true
	}
}

func WifiStop() {
	if !isNetConnect() {
		log.Println(log.ErrorLog, "WifiStop: internet is down")
		toastNetworkError(false)
		return
	}

	wifiStopApi()
}

func WifiSeek(pos uint32) {
	if !isNetConnect() {
		log.Println(log.ErrorLog, "WifiSeek: internet is down")
		toastNetworkError(false)
		return
	}
	wifiSeekApi(pos)
}

func WifiIsOnline() bool {
	return true
}

func WifiIfForcePause() bool {
	// 是否需要强制暂停，返回false，只有在蓝牙这种系统控制播放的场景，才需要设置为true
	return false
}

func WifiPlayNext(arg interface{}) {
	if !isNetConnect() {
		log.Println(log.ErrorLog, "WifiPlayNext: internet is down")
		toastNetworkError(false)
		return
	}
	wifiNextApi(arg)
}

func WifiPlayPre(arg interface{}) {
	if !isNetConnect() {
		log.Println(log.ErrorLog, "WifiPlayPre: internet is down")
		toastNetworkError(false)
		return
	}
	wifiPreApi(arg)
}

func WifiPrepareNext() {
	wifiPrepareNextApi()
}

func WifiGetSUpportedSCmd() []SCMD {

	return nil
}

func WifiSetArg(arg ...interface{}) bool {
	if WIFI_SET_ARG_LEN == len(arg) {
		switch arg[0].(type) {
		case *ServerMusicList, *ServerMusicLists, *AppPlayReq:
			wifiPlayArg = arg[0]
		default:
			log.Println(log.ErrorLog, "arg0:", arg[0])
			goto errOut
		}
		wifiArgHasSet = true
		return true
	} else {
		log.Println(log.ErrorLog, "len:", len(arg))
	}

errOut:
	log.Printf(log.ErrorLog, "err arg params:%+v\n", arg)
	wifiArgHasSet = false
	return false
}

func WifiGetPlayerName() string {
	return WIFI_PLAYER_NAME
}

func WifiPlayerStatusChange(status PlayerDetail) {
	wifiPlayerStHd(status)
}

func WifiDebug() string {
	var ret string
	ret += fmt.Sprintf("PlayListSrcRec:%+v\n", PlayListSrcRec)
	return ret
}

func InsertSongstoPlayList(e interface{}, replace bool) {
	defer func() {
		if playerRecoverLevel <= HIGH_RECOVER_LEVEL {
			if err := recover(); err != nil {
				log.Println(log.ErrorLog, err)
			}
		}
	}()

	var songs *[]SongInfo
	var lenType MusicLenType = 0
	var topIndex MusicLenType
	var srcType MusicSrcType
	var listId string
	var tagName string

	switch eVal := e.(type) {
	case *ServerMusicList:
		songs = &(eVal.MusicList.SongList)
		lenType = MusicLenType(len(e.(*ServerMusicList).MusicList.SongList))
		topIndex = MusicLenType(eVal.MusicList.Index)
		srcType = eVal.MusicList.Type
		tagName = eVal.Oftag
		listId = eVal.MusicList.Id

		log.Println(log.DebugLog, "InsertSongstoPlayList Has more musics:", eVal.MusicList.HasMore)
	case *ServerMusicLists:
		songs = &(eVal.MusicLists[0].SongList)
		lenType = MusicLenType(len(e.(*ServerMusicLists).MusicLists[0].SongList))
		topIndex = MusicLenType(eVal.MusicLists[0].Index)
		srcType = eVal.MusicLists[0].Type
		tagName = eVal.Oftag
		listId = eVal.MusicLists[0].Id

		log.Println(log.DebugLog, "InsertSongstoPlayList Has more musics:", eVal.MusicLists[0].HasMore)
		log.Println(log.DebugLog, "InsertSongstoPlayList Has more Lists:", PlayListSrcRec.HasMore)
	default:
		log.Println(log.WarningLog, "InsertSongstoPlayList err params")
		return
	}

	if nil != songs && len(*songs) > 0 && TOP3_RCMD_SONG == (*songs)[0].SongType {
		for k := range *songs {
			(*songs)[k].MusicSrc = srcType
			(*songs)[k].MusicListId = listId
			(*songs)[k].TagName = tagName
		}
	}

	if replace {
		log.Println(log.DebugLog, "replace list, lenType:", lenType, "  topIndex:", topIndex)
		// 更新播放列表信息
		tmp := LocalMusicList[GetMusicListIndex()].GetCurPos()
		LocalMusicList[CUR_MUSIC_LIST].ReplaceBySlice(songs, lenType, 0, topIndex)
		LocalMusicList[RANDOM_MUSIC_LIST].ReplaceBySlice(songs, lenType, 0, topIndex)
		LocalMusicList[GetMusicListIndex()].SetCurPos(tmp)
	} else {
		log.Println(log.DebugLog, "add list, lenType:", lenType, "  topIndex:", topIndex)
		// 更新播放列表信息
		tmp := LocalMusicList[GetMusicListIndex()].GetCurPos()
		LocalMusicList[CUR_MUSIC_LIST].AddBySlice(songs, lenType, 0, topIndex)
		LocalMusicList[RANDOM_MUSIC_LIST].AddBySlice(songs, lenType, 0, topIndex)
		LocalMusicList[GetMusicListIndex()].SetCurPos(tmp)
	}

}

func KeyTriggerPlayorPause() {
	log.Println(log.DebugLog, "Key trig play or pause")
	if MUSIC_ST_PAUSED == wifiPlayerSt.ContinuousTaskSt {
		// 恢复播放,此时有时间参数的处理逻辑
		playMusic(nil)
	} else if MUSIC_ST_PLAYING == wifiPlayerSt.ContinuousTaskSt {
		// 暂停音乐
		sendMusicCmd(PlayerType_Wifi,CMD_PLAYER_PAUSE)
	}
}

func WifiMusicFilterSet(tts *string, denyinfo []DenyInfo) bool {
	var hasCurPlayInfo bool = false // 否定的内容是否有当前播放的歌曲或者歌手
	songInfo, errGetSong := GetCurWifiSongInfo()

	if nil != denyinfo {
		for _, tmp := range denyinfo {
			if tmp.Type == ARTIST_NAME_FILTER {
				if nil != tmp.NameData {
					for _, id := range tmp.NameData {
						err := LocalMusicFilter.Push(tmp.Type, &id)
						if nil != err {
							log.Println(log.WarningLog, err.Error())
						}
						if nil == errGetSong {
							//if songInfo.ArtistName == id {
							//	hasCurPlayInfo = true
							//}
							if IsArtistNameDeny(songInfo.ArtistName, id) {
								hasCurPlayInfo = true
							}
						}
					}
				}
			} else {
				if nil != tmp.Data {
					for _, id := range tmp.Data {
						tmpsongId := id
						err := LocalMusicFilter.Push(tmp.Type, &tmpsongId)
						if nil != err {
							log.Println(log.WarningLog, err.Error())
						}
						if nil == errGetSong {
							switch tmp.Type {
							case SONG_ID_FILTER:
								if songInfo.Id == id {
									hasCurPlayInfo = true
								}
							case ALBUM_ID_FILTER:
								if songInfo.AlbumId == id {
									hasCurPlayInfo = true
								}
							default:

							}
						}
					}
				}
			}
		}
	}
	//FilterMusic(tts)
	return hasCurPlayInfo
}
