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

public class RecipeSelectDialog : MonoBehaviour
{
    private static readonly string CallbackTag = "RecipeSelectDialogCallback";
    private static readonly int OpenTrigger = Animator.StringToHash("OpenTrigger");
    private static readonly int CloseTrigger = Animator.StringToHash("CloseTrigger");
    
    [SerializeField] private Animator backgroundAnimator;
    [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().Take(1).Subscribe(_ =>
        {
            transform.SetLocalScale(0);
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.25f, () =>
            {
                LocalCacheManager.Load<Action>(CallbackTag, null)?.Invoke();
                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 <= gameData.ViewedShopLevel)
            {
                // レシピ開放
                gameData.MyRecipes = new List<int>(gameData.MyRecipes){productData.id}.ToArray();
                gameData.DailyRecipeGetCount++;
                hasRecipe = true;
            }
            if (hasRecipe)
            {
                view.SetLockPanel(false);
                view.RecipeClickObservable.ThrottleFirst(TimeSpan.FromSeconds(.3f)).Subscribe(_ =>
                {
                    LocalCacheManager.Save(PopcornGameManager.CookingDataTag, productData);
                    RecipeDetailView.ShowDialog(() =>
                    {
                        if (gameData.isFirstPlay)
                        {
                            LocalCacheManager.Load<Action>(CallbackTag, null)?.Invoke();
                        }
                    });
                }).AddTo(this);
            }
            else
            {
                view.SetLockPanel(true);
            }
        }
        LayoutRebuilder.ForceRebuildLayoutImmediate(content);
        scrollRect.verticalNormalizedPosition = 1;
        
        if (gameData.isFirstPlay)
        {
            scrollRect.vertical = false;
            // マスク表示
            var view = content.GetChild(0).GetComponent<RecipeView>();
            var viewRectTransform = view.transform.GetChild(0) as RectTransform;
            var go = TutorialManager.Instance.ShowTutorialMask(transform.parent, viewRectTransform);
            view.RecipeClickObservable.Take(1).Subscribe(_ =>
            {
                DestroyImmediate(go);
            }).AddTo(this);
        }
    }

    public static void ShowDialog(ProductViewType type, Action onClose = null)
    {
        LocalCacheManager.Save(Const.ProductViewTypeTag, type);
        LocalCacheManager.Save(CallbackTag, onClose);
        TransitionManager.Instance.LoadSceneAdditive(GameScenes.Recipe);
    }
}
