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


namespace GeneralBehaviour
{
    public class UpdateLayout : MonoBehaviour
    {
        List<ContentSizeFitter> listContentSizeFitter = new List<ContentSizeFitter>();


        void Reset()
        {
            listContentSizeFitter.Clear();
            //Debug.Log("listContentSizeFitter.count : " + listContentSizeFitter.Count );
        }

        internal void Initialize()
        {
            ContentSizeFitter myLayoutGroup = this.GetComponent<ContentSizeFitter>();
            if (myLayoutGroup != null)
                listContentSizeFitter.Add(myLayoutGroup);

            //ParseLayoutGroup(transform);

            ContentSizeFitter[] csf = transform.GetComponents<ContentSizeFitter>();
            for (int i = 0, length = csf.Length; i < length; i++)
            {
                listContentSizeFitter.Add(csf[i]);
            }
        }


        void ParseLayoutGroup(Transform layoutGroupTran)
        {
            for (int i = 0, length = layoutGroupTran.childCount; i < length; i++)
            {
                ContentSizeFitter layoutGroup = layoutGroupTran.GetChild(i).GetComponent<ContentSizeFitter>();
                if (layoutGroup != null)
                {
                    listContentSizeFitter.Add(layoutGroup);
                    ParseLayoutGroup(layoutGroup.transform);
                }
            }

            //for (int i = 0, length = layoutGroupTran.childCount; i < length; i++)
            //{
            //    ContentSizeFitter layoutGroup = layoutGroupTran.GetChild(i).GetComponent<ContentSizeFitter>();
            //    if (layoutGroup != null)
            //        ParseLayoutGroup(layoutGroup.transform);
            //}        
        }

        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="needReread">是否需要重新读取LayoutGroup</param>
        public void Refresh(bool needReread = true)
        {
            if (gameObject.activeInHierarchy)
                StartCoroutine(DelayRefresh(needReread));
        }

        IEnumerator DelayRefresh(bool needReread = false)
        {
            if (needReread)
            {
                Reset();

                yield return 0;
                Initialize();
            }

            yield return 0;

            for (int i = listContentSizeFitter.Count - 1; i >= 0; i--)
            {
                //Debug.Log(i.ToString());
                LayoutRebuilder.ForceRebuildLayoutImmediate(listContentSizeFitter[i].GetComponent<RectTransform>());
            }
        }
    }

}