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

public class Market : MonoBehaviour
{
    public static readonly int ShopStockCount = 21;

    [SerializeField] private ShopStockView stockView;

    [SerializeField] private MarketCartView cartView;
    // Start is called before the first frame update
    void Start()
    {
        var gameData = GameDataManager.GameData;
        CoinManager.Instance.ChangeCoin(gameData.coin);
        // 在庫数表示
        stockView.SetStock(gameData.StorageTanks);

        // 全レシピ
        var allRecipe = RecipeData.GetAllRecipe();
        
        StockFlavorLog();
        
        cartView.SetStock(GameDataManager.GameData.ShopStock);

        // お客さんの出現タイミング(10秒間に１回)
        Observable.Timer(TimeSpan.FromSeconds(2f), TimeSpan.FromSeconds(10f))
            .Subscribe(_ =>
            {
                // 品切れ
                if (GameDataManager.GameData.ShopStock.Count == 0)
                {
                    return;
                }
                // 店頭の先頭から売る
                var id = GameDataManager.GameData.ShopStock[0];
                GameDataManager.GameData.ShopStock.RemoveAt(0);
                var bonusRate = 0;
                var flavor = allRecipe.First(x => x.RecipeId == id);
                CoinManager.Instance.AddCoinWithEffect(flavor.Price * (1 + bonusRate / 100), () => { });
                // 売上反映
                GameDataManager.GameData.coin = CoinManager.Instance.OwnCoin;
                GameDataManager.SaveGameData();
                cartView.SellStock();
                // 自動補充 refill
                RefillProduct();
                stockView.SetStock(GameDataManager.GameData.StorageTanks);
                cartView.SetStock(GameDataManager.GameData.ShopStock);
                StockFlavorLog();
            }).AddTo(this);
    }

    private void RefillProduct()
    {
        // 店頭に補充
        // 手前のタンクから出し多分stockをへらす
        // へらした分を店頭リストに追加する
        // 店頭とタンクのフレーバーの扱いが違うのに注意
        // 店頭にはフレーバーごとに並び順があるのでリストに1つづつ入れる必要がある
        var gameData = GameDataManager.GameData;
        var shopSpace = ShopStockCount - gameData.ShopStock.Count;
        var index = 0;
        var tankCount = gameData.StorageTanks.Count;
        while (shopSpace > 0)
        {
            if (index > tankCount - 1)
            {
                break;
            }
            var tank = gameData.StorageTanks[index];
            var stockCount = Mathf.Min(shopSpace, tank.Stock);
            gameData.ShopStock.AddRange(Enumerable.Repeat(tank.FlavorId, stockCount));
            shopSpace -= stockCount;
            tank.Stock -= stockCount;
            gameData.StorageTanks[index] = tank;
            index++;
        }
        GameDataManager.SaveGameData();
    }

    public static void StockFlavorLog()
    {
        var gameData = GameDataManager.GameData;
        var shopStockString = "";
        foreach (var data in RecipeData.GetAllRecipe())
        {
            var shopStockCount = gameData.ShopStock.FindAll(x => x == data.RecipeId).Count;
            var tank = gameData.StorageTanks.FindAll(x => x.FlavorId == data.RecipeId).Sum(x => x.Stock);
            if (shopStockCount + tank == 0)
            {
                continue;
            }
            shopStockString += $"{data.Name} shop:{shopStockCount} tank:{tank}\n";
        }
        Debug.Log(shopStockString);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
