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

public class ItemsListAnim : MonoBehaviour {

    Action OnClearList;
    Action m_OnInitAnimEnd;

    [SerializeField]
    public Transform m_ItemsParent;
    List<IAnimItem> m_ItemsList = new List<IAnimItem>();

    UIAnim m_uiAnim;

    float perItemAppearTime = 0.2f;

    bool fadeInAnimEnd = false;


    private void Awake()
    {
        if (null == m_uiAnim) m_uiAnim = gameObject.AddComponent<UIAnim>();
    }

    private void OnDestroy()
    {
        OnClearList = null;
        m_OnInitAnimEnd = null;
    }

    public void Init(List<IAnimItem> itemsList,Transform parent)
    {
        m_ItemsList = itemsList;
        m_ItemsParent = parent;
    }

    Dictionary<int, bool> m_InitSeqToStopDict = new Dictionary<int, bool>();//init list 进程与是否停止
    int m_PreSeq = 0;//前一个进程

    void InitItemsList(Action onClearList,Action onEnd)
    {
        OnClearList = onClearList;
        StopInitList();

        int curSeq = ++m_PreSeq;
        m_InitSeqToStopDict[curSeq] = false;
        InitItem(curSeq, m_ItemsList,  m_ItemsParent, 0, perItemAppearTime, onEnd);
    }

    void StopInitList()
    {
        m_InitSeqToStopDict[m_PreSeq] = true;
        // CommonFunctions.ClearList<AnimItem>(m_ItemsList);
        if (OnClearList != null)
            OnClearList();
    }


    void InitItem(int seq, List<IAnimItem> itemsList, Transform parent,int index, float time, Action onEnd)
    {
        if (index >= itemsList.Count)
        {
            if (onEnd != null) onEnd();
            return;
        }

        //是否停止
        if (m_InitSeqToStopDict.ContainsKey(seq))
        {
            if (m_InitSeqToStopDict[seq])
            {
                m_InitSeqToStopDict.Remove(seq);
                return;
            }
        }

        var newItem = itemsList[index].NewInstance(parent,index); 

        if(newItem == null || newItem.gameObject == null)
        {
            index++;
            InitItem(seq, itemsList, parent, index, time, onEnd);
        }

        DoOneItemAnim(newItem.gameObject.GetComponent<RectTransform>(), time, () =>
        {
            index++;
            InitItem(seq, itemsList, parent, index, time, onEnd);
        });


    }
    void DoOneItemAnim(RectTransform item, float time, Action onEnd)
    {
        List<float> imgAlphas;
        List<float> txtAlphas;
        List<float> rawAlphas;
        UIAnim.GetImgTxtAlpha(item, out imgAlphas, out txtAlphas, out rawAlphas);
        m_uiAnim.SetImgTxtAlpha(item, 0);
        m_uiAnim.UIAlpha(item, imgAlphas, txtAlphas, rawAlphas, time, () =>
        {
            if (onEnd != null) onEnd();
        }, UIAnim.EaseType.Curve);

    }




}
