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

public class StorageTank
{
    // タンクID, タンク内のフレーバーID, フレーバーの個数
    public int Capacity;
    public int FlavorId;
    public int Stock
    {
        get => Stocks.Sum(x => x.Stock);
    }
    public List<ProductStockData> Stocks = new List<ProductStockData>();
    public bool IsEmpty => Stock == 0;
    public bool IsFull => Stock == Capacity;

    public void AddStock(ProductRarity rarity, int stock)
    {
        var stockData = Stocks.FirstOrDefault(x => x.Rarity == rarity);
        if (stockData is default(ProductStockData))
        {
            Stocks.Add(new ProductStockData{FlavorId = FlavorId, Rarity = rarity, Stock = stock});
            return;
        }
        stockData.Stock += stock;
    }

    public List<ProductStockData> GetStock(int wantStock)
    {
        var list = new List<ProductStockData>();
        var stockCount = Mathf.Min(wantStock, Stock);
        foreach (var stockData in Stocks)
        {
            if (stockCount == 0)
            {
                continue;
            }
            var data = new ProductStockData
            {
                FlavorId = FlavorId,
                Rarity = stockData.Rarity,
                Stock = 1
            };
            var getCount = Mathf.Min(stockCount, stockData.Stock);
            list.AddRange(Enumerable.Repeat(data, getCount));
            stockData.Stock -= getCount;
            stockCount -= getCount;
        }
        return list;
    }

    public void ClearStock()
    {
        Stocks.Clear();
    }
}

public class ProductStockData
{
    public int FlavorId;
    public ProductRarity Rarity;
    public int Stock;
}