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

[ExecuteAlways]
[RequireComponent(typeof(RectTransform))]
public class FitContentHeight : MonoBehaviour
{
    [SerializeField] float updatePeriod = 1;
    float lastCheck = 0;
    RectTransform RectTransform;
    VerticalLayoutGroup LayoutManager;

    private void Awake()
    {
        RectTransform = GetComponent<RectTransform>();
        LayoutManager = GetComponent<VerticalLayoutGroup>();
    }

    private void OnGUI()
    {
        if (!Application.isPlaying && Application.isEditor) Check();
    }

    private void LateUpdate()
    {
        if (Application.isPlaying && !Application.isEditor) Check();
    }

    void Check()
    {
        if (lastCheck >= updatePeriod)
        {
            float height = 0;
            foreach (RectTransform child in RectTransform)
            {
                height += child.rect.height;
            }

            if(LayoutManager != null)
            {
                height += (LayoutManager.spacing * RectTransform.childCount);
            }

            RectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height);
            RectTransform.anchorMin.Set(RectTransform.anchorMin.x, 1);
            RectTransform.anchorMax.Set(RectTransform.anchorMax.x, 1);

            lastCheck = 0;
        }

        lastCheck += Time.deltaTime;

        Debug.Log(lastCheck);
    }
}
