using System;
using MyGame.Scripts;
using UniRx;
using UnityEngine;
using UnityEngine.UI;

public class ShopItemExchangeView : MonoBehaviour
{
    private static readonly string ShopDataTag = "ShopItemExchangeViewShopData";
    private static readonly string CloseCallbackTag = "ShopItemExchangeViewCloseCallbackTag";
    private static readonly int OpenTrigger = Animator.StringToHash("OpenTrigger");
    private static readonly int CloseTrigger = Animator.StringToHash("CloseTrigger");
    
    [SerializeField] private Animator backgroundAnimator;
    [SerializeField] private Text name;
    [SerializeField] private Transform iconTarget;
    [SerializeField] private Button closeButton;

    private void Start()
    {
        // 表示データを受け取る
        var shopData = LocalCacheManager.Load<ShopData>(ShopDataTag);
        LocalCacheManager.Remove(ShopDataTag);
        SetData(shopData);
        closeButton.OnClickAsObservable().Take(1).Subscribe(_ =>
        {
            LocalCacheManager.Load<Action>(CloseCallbackTag, null)?.Invoke();
            transform.SetLocalScale(0);
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.25f, () =>
            {
                TransitionManager.Instance.UnloadScene(GameScenes.ExchangeAchievement);
            });
        }).AddTo(this);
    }

    private void SetData(ShopData shopData)
    {
        name.text = shopData.Name;
        iconTarget.DestroyAllChildrens();
        Instantiate(shopData.GetPrefab(), iconTarget);
    }

    public static void ShowDialog(ShopData shopData, Action onClose = null)
    {
        LocalCacheManager.Save(ShopDataTag, shopData);
        LocalCacheManager.Save(CloseCallbackTag, onClose);
        TransitionManager.Instance.LoadSceneAdditive(GameScenes.ExchangeAchievement);
    }
}
