using Streamingle.Utils.RoughConstraints;
using UnityEditor;
using UnityEngine;

namespace Streamingle.Utils.RoughConstraintsEditor
{
    [CustomPropertyDrawer(typeof(Vector3Bool))]
    public sealed class Vector3BoolDrawer : UnityEditor.PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            var x = property.FindPropertyRelative("x");
            var y = property.FindPropertyRelative("y");
            var z = property.FindPropertyRelative("z");

            position = EditorGUI.PrefixLabel(position, label);

            var previousIndent = EditorGUI.indentLevel;
            EditorGUI.indentLevel = 0;

            var gap = 4f;
            var width = (position.width - gap * 2f) / 3f;
            DrawToggle(new Rect(position.x, position.y, width, position.height), x, "X");
            DrawToggle(new Rect(position.x + width + gap, position.y, width, position.height), y, "Y");
            DrawToggle(new Rect(position.x + (width + gap) * 2f, position.y, width, position.height), z, "Z");

            EditorGUI.indentLevel = previousIndent;
        }

        private static void DrawToggle(Rect rect, SerializedProperty property, string label)
        {
            var enabled = property.boolValue;
            var previousColor = GUI.backgroundColor;
            GUI.backgroundColor = enabled ? new Color(0.55f, 0.82f, 1f) : previousColor;

            if (GUI.Button(rect, label, EditorStyles.miniButton))
            {
                property.boolValue = !enabled;
            }

            GUI.backgroundColor = previousColor;
        }
    }
}
