using System;
using KitsuneCafe.Sys;
using UnityEditor;
using UnityEngine.UIElements;
using TimeUnit = KitsuneCafe.Sys.TimeUnit;

[CustomPropertyDrawer(typeof(Duration))]
public class DurationPropertyDrawer : PropertyDrawer
{
    public override VisualElement CreatePropertyGUI(SerializedProperty property)
    {
        return new DurationField(property);
    }

    public class DurationField : VisualElement
    {
        public readonly SerializedProperty Property;
        private readonly SerializedObject serializedObject;
        private readonly SerializedProperty value;
        private readonly SerializedProperty unit;
        private readonly DoubleField durationField;

        public DurationField(SerializedProperty property, string label = null)
        {
            label ??= ObjectNames.NicifyVariableName(property.name);
            style.flexDirection = FlexDirection.Row;

            Property = property;
            serializedObject = property.serializedObject;
            value = property.FindPropertyRelative("value");
            unit = property.FindPropertyRelative("unit");

            durationField = new DoubleField(
                label
            )
            {
                value = Duration.ToDisplayValue(value.longValue, (TimeUnit)unit.intValue)
            };

            durationField.style.flexGrow = 1;

            var unitField = new EnumField
            {
                bindingPath = "unit"
            };

            unitField.style.flexGrow = 0;

            Add(durationField);
            Add(unitField);

            AddToClassList(BaseField<double>.ussClassName);
            durationField.AddToClassList(BaseField<double>.alignedFieldUssClassName);

            durationField.RegisterValueChangedCallback(OnValueChanged);
        }

        private void OnValueChanged(ChangeEvent<double> evt)
        {
            value.longValue = Duration.FromDisplayValue(evt.newValue, (TimeUnit)unit.intValue);
            serializedObject.ApplyModifiedProperties();
            serializedObject.Update();
        }

        public new void RemoveFromHierarchy()
        {
            base.RemoveFromHierarchy();
            durationField.UnregisterCallback<ChangeEvent<double>>(OnValueChanged);
        }

    }
}

