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

public class RecipeSelectDialog : MonoBehaviour
{
    [SerializeField] private ScrollRect scrollRect;
    [SerializeField] private RecipeView recipePrefab;
    [SerializeField] private Button closeButton;
    // Start is called before the first frame update
    void Start()
    {
        var gameData = GameDataManager.GameData;
        closeButton.OnClickAsObservable().Subscribe(_ =>
        {
            TransitionManager.Instance.UnloadScene(GameScenes.Recipe);
        }).AddTo(this);
        
        // レシピ一覧生成
        var content = scrollRect.content;
        content.transform.DestroyAllChildrens();
        var data = SpreadsheetDataManager.Instance.GetBaseDataList<ProductData>(Const.ProductDataSheet);
        foreach (var productData in data)
        {
            var view = Instantiate(recipePrefab, content.transform);
            view.SetRecipe(productData);
            // 所持レシピ確認
            var hasRecipe = false;
            if (gameData.MyRecipes.Contains(productData.id))
            {
                hasRecipe = true;
            }
            else if (productData.shopLevel <= HeartMeter.Instance.ShopLevel.Value)
            {
                // レシピ開放
                gameData.MyRecipes = new List<int>(gameData.MyRecipes){productData.id}.ToArray();
                hasRecipe = true;
            }
            if (hasRecipe)
            {
                view.SetLockPanel(false);
                view.RecipeClickObservable.Subscribe(_ =>
                {
                    LocalCacheManager.Save(PopcornGameManager.CookingDataTag, productData);
                    TransitionManager.Instance.LoadSceneAdditive(GameScenes.RecipeChoice);
                }).AddTo(this);
            }
            else
            {
                view.SetLockPanel(true);
            }
        }
        LayoutRebuilder.ForceRebuildLayoutImmediate(content);
        scrollRect.verticalNormalizedPosition = 1;
    }
}
