using RebootKit.Editor.Utils;
using RebootKit.Engine.Foundation;
using UnityEditor;
using UnityEngine;

namespace RebootKit.Editor.PropertyDrawers {
    [CustomPropertyDrawer(typeof(ConfigVar))]
    public class CVarDrawer : PropertyDrawer {
        bool m_Expand;

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
            CVarSerializedProperties properties = CVarSerializedPropertiesFinder.Find(property);

            EditorGUILayout.BeginHorizontal();

            GUILayout.Label(label, EditorStyles.miniBoldLabel);

            properties.name.stringValue = EditorGUILayout.TextField(properties.name.stringValue);

            bool isNumber = properties.defaultValueKind.enumValueIndex == (int) CVarValueKind.Number;
            string kindLabel = isNumber ? "N" : "S";

            if (isNumber)
                GUI.color = Color.cyan;
            else
                GUI.color = Color.green;

            if (GUILayout.Button(kindLabel, GUILayout.Width(32))) properties.defaultValueKind.enumValueIndex = isNumber ? (int) CVarValueKind.String : (int) CVarValueKind.Number;

            GUI.color = Color.white;

            if (isNumber)
                properties.defaultValueNumber.doubleValue = EditorGUILayout.DoubleField(properties.defaultValueNumber.doubleValue);
            else
                properties.defaultValueString.stringValue = EditorGUILayout.TextField(properties.defaultValueString.stringValue);

            if (GUILayout.Button(m_Expand ? "H" : "S", GUILayout.MaxWidth(24))) m_Expand = !m_Expand;

            EditorGUILayout.EndHorizontal();

            if (m_Expand) {
                EditorGUILayout.PropertyField(properties.name, new GUIContent("Name"));
                EditorGUILayout.PropertyField(properties.description, new GUIContent("Description"));
                EditorGUILayout.PropertyField(properties.defaultValueKind, new GUIContent("Value Kind"));
                EditorGUILayout.PropertyField(properties.defaultValueNumber, new GUIContent("Number"));
                EditorGUILayout.PropertyField(properties.defaultValueString, new GUIContent("String"));
            }
        }
    }
}