using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using UnityEngine.UIElements;

public class TitleLayoutBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    public string perfabPath = "perfabs/titleBtn";
    void Start()
    {
    }
    public void udpateShow(string[] data, listViewBack back)
    {
        GameObject gameObjectContext = this.gameObject.GetComponent<ScrollRect>().content.gameObject;
        GameObject first = Resources.Load<GameObject>(perfabPath);

        var horizontalLayout = gameObjectContext.GetComponent<HorizontalLayoutGroup>();
        var rectTransform = gameObjectContext.GetComponent<RectTransform>();
        int count = data.Length;

        float spacingLen = 0;
        if(data.Length > 1)
        {
            spacingLen = horizontalLayout.spacing * (data.Length - 1);
        }
        float width = spacingLen + data.Length * first.transform.GetComponent<RectTransform>().sizeDelta.x + horizontalLayout.padding.left + horizontalLayout.padding.right;
        var rectTransform1 = this.GetComponent<RectTransform>();
        if (width < rectTransform1.sizeDelta.x)
        {
            width = rectTransform1.sizeDelta.x;
        }
        
        rectTransform.sizeDelta = new Vector2(width, rectTransform.sizeDelta.y);
        for (int i = 0; i < data.Length; i++)
        {
            string name = $"auto_title_{i}";
            var childTransform = gameObjectContext.transform.Find(name);
            GameObject itemObject = null;
            if (childTransform != null) {
                itemObject = childTransform.gameObject;
                back(itemObject, i, ListViewBackTypeEnum.update);
            }
            else
            {
                itemObject = Instantiate(first);
                itemObject.name = name;
                itemObject.transform.SetParent(gameObjectContext.transform);
                back(itemObject, i, ListViewBackTypeEnum.create);
            }
        }
        
        for (int i = data.Length; i < 100000000; i++)
        {
            string name = $"auto_title_{i}";
            var childTransform = gameObjectContext.transform.Find(name);
            if (childTransform == null)
            {
                break;
            }
            GameObject.Destroy(childTransform.gameObject);
        }
            
    }
    public GameObject getObjectById(int id)
    {
        GameObject gameObjectContext = this.gameObject.GetComponent<ScrollRect>().content.gameObject;
        string name = $"auto_title_{id}";
        var transfromitem = gameObjectContext.transform.Find(name);
        if(transfromitem == null)
        {
            return null;
        }
        return transfromitem.gameObject;
    }
    // Update is called once per frame
    void Update()
    {

    }
}
