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

namespace Unity.Func.Sample.UI
{
    public class InventoryUIController : MonoBehaviour
    {
        public Transform listContent;
        public GameObject cardItemPrefab;

        [Header("物品详情")]
        public GameObject detailPanel;
        public GameObject inventoryItem;
        public TextMeshProUGUI itemName;

        public void Init(List<CardConfig.Card> cards)
        {
            DestroyAllChildren(listContent);
            detailPanel.SetActive(false);

            foreach (var card in cards)
            {
                var gameObj = Instantiate(cardItemPrefab, listContent);
                var cardItem = gameObj.GetComponent<CardItem>();
                cardItem.Init(card);
                cardItem.itemSelect.AddListener(ItemSelectHandler);
            }
        }

        private static void DestroyAllChildren(Transform parent)
        {
            for (var i = 0; i < parent.childCount; i += 1)
            {
                Destroy(parent.GetChild(i).gameObject);
            }
        }

        private void ItemSelectHandler(CardConfig.Card card)
        {
            detailPanel.SetActive(true);
            inventoryItem.GetComponent<CardItem>().Init(card);
            itemName.text = card.cardName;
        }

    }
}