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

public class ChildSkillLearnItemPanel : MonoBehaviour {

    public static ChildSkillLearnItemPanel Instance;
    private void Awake()
    {
        Instance = this;
    }

    private void OnDestroy()
    {
        Instance = null;
    }

    public GameObject _ItemPrefab;
    public Transform _Parent;
    //当前已经存在的item
    private List<ChildSkillCommonItem> _ContainerItemPrefabList = new List<ChildSkillCommonItem>();
    public delegate void _InitItemFinishCallBack();
    public void InitItemPanel(List<int> list)
    {
        StartCoroutine(CreateItemPrefab(list, () =>
        {
            for (int index = 0; index < list.Count; index++)
                _ContainerItemPrefabList[index].InitItemInfo(list[index]);
        }));
    }

    IEnumerator CreateItemPrefab(List<int> list, _InitItemFinishCallBack callBack)
    {
        yield return null;

        if(_ContainerItemPrefabList.Count > list.Count)
        {
            for (int index = 0; index < list.Count; index++)
                _ContainerItemPrefabList[index].gameObject.SetActive(true);
            for (int index = list.Count; index < _ContainerItemPrefabList.Count; index++)
                _ContainerItemPrefabList[index].gameObject.SetActive(false);
        }else
        {
            var lackCount = list.Count - _ContainerItemPrefabList.Count;
            for (int index = 0; index < lackCount; index++)
            {
                var obj = Instantiate(_ItemPrefab);
                obj.transform.SetParent(_Parent);
                obj.transform.localRotation = Quaternion.Euler(Vector3.zero);
                obj.transform.localScale = Vector3.one;

                var scriptComponent = obj.GetComponent<ChildSkillCommonItem>();
                _ContainerItemPrefabList.Add(scriptComponent);
            }
        }

        callBack.Invoke();
        yield break;
    }

    public void OnMask()
    {
        UIManager.CloseUI(UIInfo.ChildSkillLearnItemPanel);
    }

    public void RefreshItemCount()
    {
        //_ItemContainer.ForeachActiveItem<ChildSkillCommonItem>((item) => {
        //    item.RefreshItemCount();
        //});
        for(int index = 0; index < _ContainerItemPrefabList.Count; index++)
        {
            _ContainerItemPrefabList[index].RefreshItemCount();
        }
    }

    private void OnDisable()
    {
        _ContainerItemPrefabList.Clear();
    }
}