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

public class UICanvas : MonoBehaviour
{
    //main panel
    public TMPro.TMP_InputField tMP_InputField;
    public TMPro.TMP_Text tMP_Text;
    public Button loadBtn;
    public Button plyBtn;
    public Scrollbar musicTimeline;
    public TMPro.TMP_Text musicTimeText;
    public Animator animator;
    public AudioSource audioSource;

    //loading panel
    public GameObject loadingPanel;
    public Scrollbar loadingScrollbar;
    public TMPro.TMP_Text loadingText;

    private AssetBundlesManager loader;
    private string loadedAssetBundlePath;
    private const string playContent = "Play";
    private const string pauseContent = "Pause";

    // Start is called before the first frame update
    void Start()
    {
        loader = FindAnyObjectByType<AssetBundlesManager>();
        if (loadBtn != null)
        {
            loadBtn.onClick.AddListener(() => { LoadAvatar(); });
        }
        if (plyBtn != null)
        {
            plyBtn.onClick.AddListener(PlayOrPause);
        }
        UGCWebImpoter.Instance.StateChangeEvent += OnPlayStageChange;
    }

    public void LoadAvatar(string url = null)
    {
        if (animator == null)
        {
            Debug.LogError("animator is null");
            return;
        }
        loadingPanel.SetActive(true);
        loadingScrollbar.size = 0;
        loadingText.text = "0%";
        url = url ?? tMP_InputField.text;
        if (loader != null && !string.IsNullOrEmpty(url))
        {
            loadedAssetBundlePath = url;
            UGCWebImpoter.Instance.Play(url, OnAnimationLoaded, OnAudioClipLoaded, OnProgress);
        }
    }

    public void PlayOrPause()
    {
        UGCWebImpoter.PLAYSTATE playState = UGCWebImpoter.Instance.PlayState;
        if (playState == UGCWebImpoter.PLAYSTATE.Playing)
        {
            UGCWebImpoter.Instance.Pause();
        }
        else if (playState == UGCWebImpoter.PLAYSTATE.Paused || playState == UGCWebImpoter.PLAYSTATE.Stopped)
        {
            if (playState == UGCWebImpoter.PLAYSTATE.Stopped)
            {
                Transform avatar = animator.transform;
                avatar.position = Vector3.zero;
                avatar.rotation = Quaternion.identity;
            }
            UGCWebImpoter.Instance.Resume();
        }
    }

    public void OnAnimationLoaded(AnimationClip clip)
    {
        //滻animatorOverrideControllerеĶ
        if (animator != null)
        {
            Debug.Log("animation clip loaded");
            AnimatorOverrideController animatorOverrideController = animator.runtimeAnimatorController as AnimatorOverrideController;
            animatorOverrideController["dance"] = clip;
            animator.runtimeAnimatorController = animatorOverrideController;
        }
    }

    public void OnAudioClipLoaded(AudioClip clip)
    {
        if (audioSource != null)
        {
            Debug.Log($"audio clip loaded, lenth:{clip.length}");
            audioSource.clip = clip;
        }
    }

    public void OnProgress(float progress)
    {
        Debug.Log("progress: " + progress);
        if (loadingScrollbar != null)
        {
            loadingScrollbar.size = progress;
            loadingText.text = (progress * 100).ToString("0.00") + "%";
        }
        if (progress >= 1.0f)
        {
            loadingPanel.SetActive(false);
            plyBtn.interactable = true;
            Transform avatar = animator.transform;
            avatar.position = Vector3.zero;
            avatar.rotation = Quaternion.identity;
            UGCWebImpoter.Instance.Resume();
            tMP_Text.text = pauseContent;
        }
    }
    string[] contextNames;
    UGCContextConfig[] contextConfigs;

    public void UnZip()
    {
        UGCUtils.UnZipAllContexts();
        UGCUtils.GetAllUGCContextConfigs(ref contextNames, ref contextConfigs);
        foreach(string name in contextNames)
        {
            Debug.Log(name);
        }
    }

    public void GetContextHash()
    {
        if (contextConfigs == null || contextConfigs.Length == 0)
            return;

        string contextName = contextNames[0];
        UGCContextConfig contextConfig = contextConfigs[0];
        string audioName = contextConfig.audioName;
        //ȥ׺
        audioName = audioName.Substring(0, audioName.LastIndexOf('.')) + ".ab";
        string animationName = contextConfig.animationName;
        //ȥ׺
        animationName = animationName.Substring(0, animationName.LastIndexOf('.')) + ".ab";
        string audiohash;
        string animationHash;
        UGCUtils.GetUGCContextConfigHash(contextName, audioName, animationName, out audiohash, out animationHash);
        Debug.Log("audioHash: " + audiohash);
        Debug.Log("animationHash: " + animationHash);
    }

    public void OnPlayStageChange(UGCWebImpoter.PLAYSTATE state)
    {
        if (state == UGCWebImpoter.PLAYSTATE.Playing)
        {
            tMP_Text.text = pauseContent;
        }
        else
        {
            tMP_Text.text = playContent;
        }
    }

    private void Update()
    {
        if (musicTimeline != null && musicTimeText != null && audioSource != null && UGCWebImpoter.Instance.PlayState == UGCWebImpoter.PLAYSTATE.Playing)
        {
            float musicLength = UGCWebImpoter.Instance.Config == null ? 0 : UGCWebImpoter.Instance.Config.audioContext.musicLength;
            if (musicLength > 0)
            {
                musicTimeline.size = audioSource.time / musicLength;
                //  00:00/00:00ʽ
                musicTimeText.text = string.Format("{0:D2}:{1:D2}/{2:D2}:{3:D2}", (int)audioSource.time / 60, (int)audioSource.time % 60, (int)musicLength / 60, (int)musicLength % 60);
            }
        }
    }
}
