using System;
using UnityEngine;
using UnityEngine.UIElements;
using Logger = RebootKit.Engine.Foundation.Logger;

namespace RebootKit.Engine.ConsoleUI {
    public class ConsoleVC : MonoBehaviour {
        static readonly Logger s_logger = new Logger(nameof(ConsoleVC));

        [SerializeField] UIDocument m_Document;

        Label m_LabelMessage;

        VisualElement m_Root;

        ScrollView m_ScrollView;
        TextField m_TextField;

        void OnEnable() {
            m_Root = m_Document.rootVisualElement;
            m_LabelMessage = m_Root.Q<Label>("console-window-message");

            m_TextField = m_Root.Q<TextField>("console-text-field");
            m_TextField.value = string.Empty;
            m_TextField.RegisterCallback<KeyUpEvent>(ev => {
                if (ev.keyCode == KeyCode.Return) {
                    Submit();
                    ev.StopPropagation();
                }
            });

            Button submitButton = m_Root.Q<Button>("console-btn-submit");
            submitButton.RegisterCallback<ClickEvent>(_ => { Submit(); });

            Button clearButton = m_Root.Q<Button>("console-btn-clear");
            clearButton.RegisterCallback<ClickEvent>(_ => { Clear(); });

            m_ScrollView = m_Root.Q<ScrollView>("console-scrollview");

            m_TextField.schedule.Execute(() => m_TextField.Focus()).StartingIn(1);
        }

        public event Action<string> InputSubmitted = _ => { };
        public event Action ClearRequested = () => { };

        public void SetMessageContent(string message) {
            if (m_LabelMessage == null) {
                return;
            }

            m_LabelMessage.text = message;
            m_ScrollView.schedule.Execute(() => { m_ScrollView.scrollOffset = new Vector2(0, m_ScrollView.contentContainer.contentRect.height); }).StartingIn(16);
        }

        void Submit() {
            InputSubmitted.Invoke(m_TextField.value);
            m_TextField.value = string.Empty;
            m_TextField.Focus();
        }

        void Clear() {
            ClearRequested.Invoke();
            m_TextField.value = string.Empty;
        }
    }
}