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

public sealed class ApplicationExitConfirmDialogManager : MonoBehaviour
{
    private static readonly int OpenTrigger = Animator.StringToHash("OpenTrigger");
    private static readonly int CloseTrigger = Animator.StringToHash("CloseTrigger");
    [SerializeField] private Animator backgroundAnimator;
    [SerializeField] private Button backButton;
    [SerializeField] private Button closeButton;
    [SerializeField] private Button exitButton;

    private void Start()
    {
        backButton.OnClickAsObservable()
            .Merge(closeButton.OnClickAsObservable())
            .Take(1)
            .Subscribe(_ =>
            {
                transform.parent.SetLocalScale(0);
                backgroundAnimator.SetTrigger(CloseTrigger);
                this.CallWaitForSeconds(.25f, OnHide);
            }).AddTo(this);
        exitButton.OnClickAsObservable().Subscribe(_ => OnExit()).AddTo(this);
    }

    public void OnExit(){
#if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
#else
        UnityEngine.Application.Quit();
#endif
    }
    
    public void OnHide(){
        this.CallWaitForOneFrame(() => {
            TransitionManager.Instance.UnloadScene(GameScenes.ApplicationExitConfirmDialog);
        });
    }

    public static void ShowDialog(){
        TransitionManager.Instance.LoadSceneAdditive(GameScenes.ApplicationExitConfirmDialog, SceneType.ManualUnloadOnly);
    }
}