using System;
using System.Collections.Generic;

public class BackButtonManager : SingletonMonoBehaviour<BackButtonManager> {

    private Stack<Action<bool>> backActionStack = new Stack<Action<bool>>();
    private bool isEnable = true;
    public void SetEnable(){
        isEnable = true;
    }
    public void SetDisable(){
        isEnable = false;
    }

#if UNITY_ANDROID || UNITY_EDITOR
    private Action genericBackAction = ActionExtensions.EmptyAction;

    void Update(){
        if(isEnable && UnityEngine.Input.GetKeyDown(UnityEngine.KeyCode.Escape)){
            if(backActionStack.Count > 0){
                PopAction(true);
            }else{
                genericBackAction();
            }
            return;
        }
    }
#endif

    public void SetGenericAction(Action action){
#if UNITY_ANDROID || UNITY_EDITOR
        genericBackAction = action;
#endif
    }

    public void SetAction(Action action){
        SetAction(isPressedBackButton => action());
    }
    public void SetAction(Action<bool> action){
        backActionStack.Push(action);
    }

    public void PopAction(){
        PopAction(false);
    }
    private void PopAction(bool isPressedBackButton){
        // Dialog等UnloadSceneAsync中に行うとエラーが出るので握り潰し
        try{
            backActionStack.Pop()(isPressedBackButton);
        }catch(Exception){
        }
    }
    public void DestroyOneAction(){
        if(backActionStack.Count > 0){
            backActionStack.Pop();
        }
    }
    public void DestroyAllAction(){
        backActionStack.Clear();
    }
}
