using System.Collections.Generic;
using UnityEngine;

namespace YachtDice.Shop
{
    [CreateAssetMenu(fileName = "ShopCatalog", menuName = "YachtDice/Shop/Catalog")]
    public class ShopCatalog : ScriptableObject
    {
        [SerializeField] private List<ScriptableObject> items = new();

        private List<IShopItem> cachedItems;

        public IReadOnlyList<IShopItem> All
        {
            get
            {
                if (cachedItems == null) RebuildCache();
                return cachedItems;
            }
        }

        public IShopItem FindById(string id)
        {
            var all = All;
            for (int i = 0; i < all.Count; i++)
            {
                if (all[i] != null && all[i].Id == id)
                    return all[i];
            }
            return null;
        }

        private void RebuildCache()
        {
            cachedItems = new List<IShopItem>();
            for (int i = 0; i < items.Count; i++)
            {
                if (items[i] is IShopItem shopItem)
                    cachedItems.Add(shopItem);
            }
        }

        private void OnValidate() => cachedItems = null;
    }
}
