using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MusicPanel : BasePanel
{
    //当前正在播放的格子
    public MusicCell PlayingCell;

    public AudioSource AS;
    public override void OnHide(object data = null)
    {
        
    }

    public override void OnInit(object data = null)
    {
        GetControl<Button>("btnBack").onClick.AddListener(() =>{ UIMgr.Getinstance().HidePanel<MusicPanel>(); });

        AS = GetComponentInChildren<AudioSource>();
        
        #region 通过数据初始化面板

        Dictionary<string, object> paras = new Dictionary<string, object>();
        paras.Add("song_id", 1);
        HttpTool.Instance._Get("app/v1/watermelon/songs_list", paras, new Action<SongBean>((result) =>
        {
            for (int i = 0; i < result.list.Count; i++)
            {
                GameObject obj = ResMgr.Getinstance().Load<GameObject>("Cells/MusicCell");
                obj.transform.SetParent(GetControl<ScrollRect>("svMusic").content.transform);
                obj.transform.ReSet();

                obj.GetComponent<MusicCell>().OnInit(result.list[i]);
            }

        }), new Action<string, string>((code, msg) =>
        {
            Debug.unityLogger.Log("获取歌曲列表 " + code + " msg " + msg);
        }));
        #endregion
    }

    public override void OnRefresh(object data = null)
    {
        //UIMgr.GetInstance().HidePanel<MusicPanel>();
    }

    public void ChangeMusic(MusicCell cell) 
    {
        //如果正在播放的和点击的歌曲相同 表示 用户正在关闭当前播放的音乐
        if (PlayingCell == cell)
        {
            cell.OnStopMusic();
            PlayingCell = null;
            return;
        }

        PlayingCell?.OnStopMusic();

        PlayingCell = cell;

        cell.OnStartMusic();
    }

    public bool IsPlayingMusic() 
    {
        if (AS.clip == null)
            return false;

        return AS.isPlaying;
    }

    public void PlayMusic(AudioClip clip) 
    {
        AS.clip = clip;
        AS.loop = true;
        AS.Play();
    }

    public void StopMusic() 
    {
        AS.Stop();
        AS.clip = null;
    }

}
