﻿/*
MIT License

Copyright(c) 2019 Mitchel Thompson
www.angryarugula.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.UI;

namespace Arugula.UI
{
    public class MenuManager : MonoBehaviour
    {
        static MenuManager instance;

        public static void ShowPrimary(string name) => instance._ShowPrimary(name);
        public static void GoBack() => instance._GoBack();
        public static void Show(string name) => instance._Show(name);
        public static void Hide(string name, bool disable = true) => instance._Hide(name, disable);
        public static void ClearHistory() => instance._ClearHistory();

        public InputSystemUIInputModule inputModule;
        public List<GameObject> menus;
        public GameObject primaryMenu;

        Stack<GameObject> history = new Stack<GameObject>();
        bool ignoreBack = false;

        private void OnEnable()
        {
            instance = this;

            InputAction cancelAction = inputModule.actionsAsset.FindActionMap("UI").FindAction("Cancel");
            cancelAction.performed += CancelCallback;

            InputAction submitAction = inputModule.actionsAsset.FindActionMap("UI").FindAction("Submit");
            submitAction.performed += SubmitCallback; ;
        }

        private void SubmitCallback(InputAction.CallbackContext obj)
        {
            //TODO:  Make sure this doesn't actually pass the Submit event down to the object...
            if (EventSystem.current.currentSelectedGameObject == null)
            {
                //TODO: Ugh.  Can't use the event...
                primaryMenu?.GetComponent<MenuAutoSelect>()?.Invoke("Select", 0.01f);
            }

        }

        private void CancelCallback(InputAction.CallbackContext obj)
        {
            _GoBack();
        }

        private void Start()
        {
            if (primaryMenu != null && !primaryMenu.activeSelf)
                ShowPrimary(primaryMenu.name);
        }

        private void OnDisable()
        {
            instance = null;
        }

        GameObject GetMenu(string name)
        {
            return menus.FirstOrDefault(x => x.name.ToLower() == name.ToLower());
        }

        void _Show(string name)
        {
            GameObject menu = GetMenu(name);
            menu.SetActive(true);
            menu.GetComponent<MenuTransition>().Show();
        }

        void _Hide(string name, bool disable = true)
        {
            GameObject menu = GetMenu(name);
            menu.GetComponent<MenuTransition>().Hide(() => { if (disable) menu.SetActive(false); });
        }

        void _ShowPrimary(string name)
        {
            GameObject menu = GetMenu(name);

            if (menu == null)
                throw new System.Exception($"Menu '{name}' not found!");

            ignoreBack = true;
            EventSystem.current.SetSelectedGameObject(null);
            if (primaryMenu != null)
            {
                if (primaryMenu.GetComponent<MenuTransition>())
                {
                    primaryMenu.GetComponent<MenuTransition>().Hide(
                    () =>
                    {
                        primaryMenu.SetActive(false);
                        menu.SetActive(true);
                        menu.GetComponent<MenuTransition>().Show();
                        if (history.Count > 0 && history.Peek() == menu)
                            history.Pop();
                        else if (primaryMenu != menu)
                            history.Push(primaryMenu);

                        primaryMenu = menu;
                        if (primaryMenu.GetComponent<MenuAutoSelect>())
                            primaryMenu.GetComponent<MenuAutoSelect>().Select();
                        ignoreBack = false;
                    });
                }
                else
                {
                    primaryMenu.SetActive(false);
                    history.Push(primaryMenu);
                    primaryMenu = menu;
                    menu.SetActive(true);
                    if (primaryMenu.GetComponent<MenuAutoSelect>())
                        primaryMenu.GetComponent<MenuAutoSelect>().Select();
                    ignoreBack = false;
                }

            }
            else
            {
                menu.SetActive(true);
                if (menu.GetComponent<MenuTransition>() != null)
                    menu.GetComponent<MenuTransition>().Show();

                primaryMenu = menu;
                if (primaryMenu.GetComponent<MenuAutoSelect>())
                    primaryMenu.GetComponent<MenuAutoSelect>().Select();
                ignoreBack = false;
            }
        }

        void _GoBack()
        {
            if (ignoreBack)
                return;

            if (history.Count == 0)
                return;

            ShowPrimary(history.Peek().name);
        }

        void _ClearHistory()
        {
            history.Clear();
        }
    }

}
