using System.Text;
using RebootKit.Engine.Foundation;
using RebootKit.Engine.Input;
using RebootKit.Engine.Main;
using UnityEngine;
using UnityEngine.InputSystem;
using Logger = RebootKit.Engine.Foundation.Logger;

namespace RebootKit.Engine.ConsoleUI {
    public class ConsoleUIService : ServiceMonoBehaviour {
        static readonly Logger s_Logger = new Logger(nameof(ConsoleUIService));

        [SerializeField] ConsoleVC m_ConsoleVC;
        [SerializeField] ScriptableInputAction m_ToggleAction;

        readonly StringBuilder m_Content = new StringBuilder();

        public bool IsVisible => m_ConsoleVC.gameObject.activeSelf;

        void Awake() {
            SetVisibility(false);
        }

        void OnEnable() {
            s_Logger.Info("OnEnable console");

            m_ToggleAction.Action.Enable();
            m_ToggleAction.Action.performed += OnToggleAction;

            m_ConsoleVC.InputSubmitted += OnUserInput;
            m_ConsoleVC.ClearRequested += Clear;
            RR.Console.OnOutputMessage += Write;
        }

        void OnDisable() {
            m_ToggleAction.Action.performed -= OnToggleAction;

            m_ConsoleVC.InputSubmitted -= OnUserInput;
            m_ConsoleVC.ClearRequested -= Clear;
            RR.Console.OnOutputMessage -= Write;
        }

        public override void Dispose() {
        }

        public void ToggleVisibility() {
            SetVisibility(!IsVisible);

            if (IsVisible) {
                RR.Input.DisableControls();
                RR.Input.UnlockCursor();

                m_ConsoleVC.SetMessageContent(m_Content.ToString());
            } else {
                RR.Input.EnableControls();
                RR.Input.LockCursor();
            }
        }

        void OnUserInput(string input) {
            RR.Console.WriteToOutput("> " + input);
            RR.Console.Execute(input);
        }

        public void SetVisibility(bool visible) {
            m_ConsoleVC.gameObject.SetActive(visible);
        }

        public void Write(string message) {
            m_Content.AppendLine(message);
            m_ConsoleVC.SetMessageContent(m_Content.ToString());
        }

        public void Clear() {
            m_Content.Clear();
            m_ConsoleVC.SetMessageContent(string.Empty);
        }

        void OnToggleAction(InputAction.CallbackContext obj) {
            ToggleVisibility();
        }
    }
}