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

public class PopNoticeLogic : MonoBehaviour {

    public static PopNoticeLogic Instance;

    public GameObject panel;
    public Animator panelAnim;
    public List<Animator> textAnim;
    public List<Text> textDesc;

    public float showTime;
    public float switchInternal;
    public float closeTime;
    private float hasColdTime;

    private int curIndex = 0;

    private string textIdle = "None";
    private string textShow = "Show";
    private string textHide = "Hide";

    private string panelShow = "Show";
    private string panelHide = "Hide";
    private static int count = 0;
    private AnimatorStateInfo animatorInfo;

    private Coroutine coldTimeCtr;
    private Queue<string> msgQueue = new Queue<string>();

    void Awake()
    {
        Instance = this;
    }

    private void OnDestroy()
    {
        Instance = null;
    }

    // 入口
    public void PopStringInfo(string msg)
    {
        msgQueue.Enqueue(msg);
        animatorInfo = panelAnim.GetCurrentAnimatorStateInfo(0);
        if (!panel.activeInHierarchy || animatorInfo.IsName(panelHide))
        {
            StopAllCoroutines();

            panel.SetActive(true);
            panelAnim.Play(panelShow);
            textDesc[curIndex].text = msgQueue.Peek();
            StartCoroutine(CountShowTime());
        }
    }

    private IEnumerator CountShowTime()
    {
        if(coldTimeCtr != null)
        {
            StopCoroutine(coldTimeCtr);
            coldTimeCtr = null;
        }

        yield return new WaitForSeconds(showTime + switchInternal);

        DeQueue();
    }

    private IEnumerator CountColdTime()
    {
        hasColdTime = 0.0f;
        while (true)
        {
            hasColdTime += Time.deltaTime;
            if(hasColdTime > closeTime)
            {
                panelAnim.Play(panelHide);
                yield break;
            }

            yield return 0;
        }
    }

    private void DeQueue()
    {
        msgQueue.Dequeue();

        if(msgQueue.Count > 0)
        {
            textAnim[curIndex].Play(textHide);
            curIndex = (curIndex + 1) % 2;
            textAnim[curIndex].Play(textShow);
            textDesc[curIndex].text = msgQueue.Peek();
            StartCoroutine(CountShowTime());
        }
        else
        {
            coldTimeCtr = StartCoroutine(CountColdTime());
        }
    }

    private void OnEnable()
    {
        panel.SetActive(false);
        for(int i = 0; i < textAnim.Count; ++i)
        {
            textAnim[i].Play(textIdle);
        }
    }
}