﻿#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using static ABI.CCK.Scripts.Editor.SharedComponentGUI;

namespace ABI.CCK.Components
{
    [CanEditMultipleObjects]
    [CustomEditor(typeof(CVRInputFieldKeyboardHandler))]
    public class CCK_CVRInputFieldKeyboardHandlerEditor : Editor
    {
        private CVRInputFieldKeyboardHandler _handler;

        private SerializedProperty m_KeyboardModeProp;
        
        #region Unity Events

        private void OnEnable()
        {
            if (!target) return;
            _handler = (CVRInputFieldKeyboardHandler)target;
            
            m_KeyboardModeProp = serializedObject.FindProperty(nameof(CVRInputFieldKeyboardHandler.keyboardMode));
        }
        
        public override void OnInspectorGUI()
        {
            if (!_handler)
                return;

            serializedObject.Update();

            EditorGUILayout.HelpBox("This component lets you override the display behaviour of the build-in keyboard for in-world input fields.", MessageType.Info);
            
            Draw_MissingComponentWarnings();
            Draw_Configuration();

            serializedObject.ApplyModifiedProperties();
        }
        
        #endregion Unity Events

        #region Drawing Methods
        
        private void Draw_MissingComponentWarnings()
        {
            if (!_handler.TryGetComponent(out RectTransform _))
                EditorGUILayout.HelpBox("This component is expected to be on a GameObject with a RectTransform!", MessageType.Warning);

            if (_handler.TryGetComponent(out InputField _) && _handler.TryGetComponent(out TMPro.TMP_InputField _))
                EditorGUILayout.HelpBox("This component expects an Input Field on the same GameObject!", MessageType.Warning);
        }
        
        private void Draw_Configuration()
        {
            using (new LabelScope("Configuration"))
            {
                using (new EditorGUI.IndentLevelScope())
                    DrawConfiguration();
            }
        }

        private void DrawConfiguration()
        {
            GUILayout.BeginVertical();

            EditorGUILayout.PropertyField(m_KeyboardModeProp);
            
            // I think is self explain
            // Rect controlRect = EditorGUILayout.GetControlRect();
            // bool willOpen = (CVRInputFieldKeyboardHandler.KeyboardMode)m_KeyboardModeProp.intValue == CVRInputFieldKeyboardHandler.KeyboardMode.OpenKeyboard;
            // EditorGUI.HelpBox(controlRect, $"This Input Field will {(willOpen ? "open" : "not open")} the built-in keyboard.", MessageType.Info);

            GUILayout.EndVertical();
        }

        #endregion Drawing Methods
    }
}
#endif