using System;
using UnityEngine;
using ConjureOS.Input;

namespace ConjureOS.ArcadeMenu
{
    public class ConjureArcadeMenu : MonoBehaviour
    {
        public event Action OnOpen;

#if !ENABLE_INPUT_SYSTEM && ENABLE_LEGACY_INPUT_MANAGER
        [SerializeField]
        private string homeButton = "Home";
#endif
        
        public bool IsOpened { get; private set; } = false;
        
        private void Start() 
        {
#if !ENABLE_INPUT_SYSTEM && ENABLE_LEGACY_INPUT_MANAGER
            if (!IsButtonAvailable(homeButton))
            {
                Debug.LogWarning(
                    $"ConjureOS: {nameof(homeButton)} in {nameof(ConjureArcadeMenu)} must be a valid action name ('{homeButton}' is not set up). " +
                    "To modify actions, go to 'Edit > Project Settings > Input Manager'.");
            }
#endif
        }
        
#if !ENABLE_INPUT_SYSTEM && ENABLE_LEGACY_INPUT_MANAGER
    private bool IsButtonAvailable(string buttonName)
    {
        try
        {
            UnityEngine.Input.GetButton(buttonName);
            return true;
        }
        catch (ArgumentException)
        {
            return false;
        }
    }
    
    private bool WasButtonPressedThisFrame(string buttonName)
    {
        try
        {
            return UnityEngine.Input.GetButtonDown(buttonName);
        }
        catch (ArgumentException)
        {
            return false;
        }
    }
#endif

        private void Update()
        {
#if ENABLE_INPUT_SYSTEM
            foreach (ConjureArcadeController arcadeController in ConjureArcadeController.allControllers)
            {
                if (arcadeController.home.wasPressedThisFrame)
                {
                    OpenArcadeMenu();
                }
            }
#elif ENABLE_LEGACY_INPUT_MANAGER
            if (WasButtonPressedThisFrame(homeButton))
            {
                OpenArcadeMenu();
            }
#endif
        }

        private void OpenArcadeMenu()
        {
            if (IsOpened)
            {
                return;
            }
            IsOpened = true;

            // This will eventually open the arcade menu.
            // However, for now, it will only close the game.
            OnOpen?.Invoke();
            
#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#endif
            Application.Quit();
        }
    }
}