/*
<copyright file="BGGCActionDrawer.cs" company="BansheeGz">
    Copyright (c) 2018-2022 All Rights Reserved
</copyright>
*/

using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;

namespace BansheeGz.BGDatabase.Editor
{
    public abstract class BGGCActionDrawer<T> : PropertyDrawer where T: BGGCAction
    {
        private Object target;
        private SerializedProperty serializedProperty;
        protected T action;
        protected VisualElement root;

        // protected void Save() => Undo.RecordObject(target, "action changed");

        public override VisualElement CreatePropertyGUI(SerializedProperty property)
        {
            serializedProperty = property;
            target = property.serializedObject.targetObject;
            action = (T)property.managedReferenceValue;

            root = new VisualElement();
            Create();
            root.Bind(property.serializedObject);
            return root;
        }

        protected virtual void Create()
        {
            
        }
        
        protected PropertyField PropEditor(string name, string label = null) => PropEditor(name, out var property, label);

        protected PropertyField PropEditor(string name, out SerializedProperty property, string label = null)
        {
            property = Find(name);
            var field = new PropertyField(property, label ?? property.displayName);
            Add(field);
            return field;
        }

        protected SerializedProperty Find(string name) => serializedProperty.FindPropertyRelative(name);

        protected void Add(VisualElement field) => root.Add(field);

        protected void RepaintRoot() => root.MarkDirtyRepaint();
    }
}