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

public class TastingView : MonoBehaviour
{
    public static readonly string TastingDataTag = "TastingData";
    private static readonly int OpenTrigger = Animator.StringToHash("OpenTrigger");
    private static readonly int CloseTrigger = Animator.StringToHash("CloseTrigger");
    
    [SerializeField] private Animator backgroundAnimator;
    [SerializeField] private Button closeButton;
    [SerializeField] private Button tastingButton;
    [SerializeField] private Text popcornName;
    [SerializeField] private Transform packageImageTarget;

    private void Start()
    {
        var data = LocalCacheManager.Load<(IObservable<(int tankNum, ProductData productData)> selectedObservable, Action closeButtonAction, Action tastingButtonAction)>(TastingDataTag);
        data.selectedObservable.Subscribe(x =>
        {
            popcornName.text = x.productData.name;
            packageImageTarget.DestroyAllChildrens();
            Instantiate(x.productData.GetIconPrefab(), packageImageTarget);
        }).AddTo(this);
        closeButton.OnClickAsObservable().Take(1).Subscribe(_ =>
        {
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.5f, () =>
            {
                data.closeButtonAction?.Invoke();
                TransitionManager.Instance.UnloadScene(GameScenes.Tasting);
            });
        }).AddTo(this);
        tastingButton.OnClickAsObservable().ThrottleFirst(TimeSpan.FromSeconds(.3f)).Subscribe(_ =>
        {
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.5f, () =>
            {
                data.tastingButtonAction?.Invoke();
                TransitionManager.Instance.UnloadScene(GameScenes.Tasting);
            });
        }).AddTo(this);
    }
}