using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class MarketCartView : MonoBehaviour
{
    [SerializeField] private List<Transform> popcornPositions;
    private List<ProductData> productDataList = new List<ProductData>();
    public void Initialize()
    {
        productDataList = SpreadsheetDataManager.Instance.GetBaseDataList<ProductData>(Const.ProductDataSheet);
    }
    
    private void ResetDisplay()
    {
        foreach (var popcorn in popcornPositions)
        {
            popcorn.DestroyAllChildrens();
        }
    }

    public void SetStock(List<(int index, ProductStockData stockData)> shopStocks, bool animate = true )
    {
        ResetDisplay();
        // 陳列
        if (animate)
        {
            var i = 0;
            foreach (var stock in shopStocks)
            {
                this.CallWaitForSeconds(.05f * i, () =>
                {
                    Refill(stock.index, stock.stockData, animate);
                });
                i++;
            }
        }
        else
        {
            foreach (var stock in shopStocks)
            {
                Refill(stock.index, stock.stockData, animate);
            }
        }
    }

    public void Refill(int index, ProductStockData stockData, bool animate = true)
    {
        popcornPositions[index].DestroyAllChildrens();
        if (productDataList.FirstOrDefault(data => data.id == stockData.FlavorId)?.GetMarketPrefab() is MarketPopcornView prefab)
        {
            var view = Instantiate(prefab, popcornPositions[index]);
            view.ChangeRarity(stockData.Rarity);
            view.SetActive(true, animate);
        }
    }

    public void SellStock(int index)
    {
        popcornPositions[index].DestroyAllChildrens();
    }
}
