using UnityEngine;
using System;
using System.Collections.Generic;
using System.Reflection;
using Octopus.Simulator;
using UnityEngine.UI;

public class Panel_LogicData : MonoBehaviour
{
    List<LogicDataInfoItem> infoList = new List<LogicDataInfoItem>();
    [SerializeField]
    LogicDataInfoItem logicItem;
    RectTransform rect;
    [SerializeField]
    RectTransform contentRect;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        FindAnyObjectByType<LogicDataManager>().OnLogicButtonClicked += OnLogicDataSelected;
        rect = GetComponent<RectTransform>();
    }

    void ClearItem()
    {
        foreach (var i in infoList)
        {
            Destroy(i.gameObject);
        }
        infoList.Clear();
    }

    void OnLogicDataSelected(ILogicItem item)
    {
        ClearItem();

        Type type=item.GetType();
        switch (item.ItemType)
        {
            case LogicItemType.Queue:
                type = (item as LogicQueue).GetType();
                break;
            case LogicItemType.Resource:
                type = (item as LogicResource).GetType();
                break;
            case LogicItemType.Component:
                type = (item as LogicComponent).GetType();
                break;
        }
        FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
        float itemHeight = logicItem.GetComponent<RectTransform>().rect.height;
        float panelHeight = fields.Length * itemHeight;
        rect.sizeDelta = new Vector2(rect.sizeDelta.x, panelHeight);
        for(int i = 0; i < fields.Length; i++)
        {
            var rawValue = fields[i].GetValue(item);
            var value = rawValue?.ToString() ?? "";
            var ilogicitem = Instantiate(logicItem, rect);
            ilogicitem.GetComponent<RectTransform>().anchoredPosition = new Vector2(ilogicitem.GetComponent<RectTransform>().anchoredPosition.x, -itemHeight * i);
            ilogicitem.Set(fields[i].Name, value);
            infoList.Add(ilogicitem);
        }
        LayoutRebuilder.ForceRebuildLayoutImmediate(contentRect);
    }
}
