using Extensions;
using Interactivity.Events;
using TPUModelerEditor;
using UnityEditor;
using UnityEngine;
using Utility.Attributes;

namespace Editor.PropertyDrawers
{
    [CustomPropertyDrawer(typeof(ExposeAttribute))]
    public class ScriptableExposerDrawer : PropertyDrawer
    {
        bool b = false;
        private SerializedObject scriptableSerializedObject;

        public override void OnGUI(Rect position, SerializedProperty property,
            GUIContent label)
        {
            EditorGUI.BeginChangeCheck();


            if (property.objectReferenceValue != null && (fieldInfo.FieldType.IsSubclassOf(typeof(ScriptableObject)) ||
                                                          fieldInfo.FieldType == typeof(ScriptableObject)))
            {
                //Create a new rect to create some space for the toggle button
                Rect fieldPos = new Rect(position.x + (position.width / 2f), position.y, (position.width / 2f),
                    position.height);
                EditorGUI.PropertyField(fieldPos, property, new GUIContent());

                //Create a new rect to set the size of the toggle button by half so that it fits in the UI.
                Rect foldoutRect = new Rect(position.x, position.y, position.width / 2f, position.height);
                b = EditorGUI.Toggle(foldoutRect, b, GUIStyles.defaultButtonStyle);
                foldoutRect.Set(position.x + (position.width / 8f), position.y, position.width / 4f, position.height);
                EditorGUI.LabelField(foldoutRect, label);

                //If the toggle is active, draw the exposed editor.
                if (b)
                    ExposeScriptableObject(property);
            }
            else
            {
                EditorGUI.PropertyField(position, property, label);
            }


            if (EditorGUI.EndChangeCheck())
            {
                property.serializedObject.ApplyModifiedProperties();
            }
        }

        private void ExposeScriptableObject(SerializedProperty property)
        {
            EditorGUILayout.BeginVertical("box");
            var e = UnityEditor.Editor.CreateEditor(property.Copy().objectReferenceValue);
            e.OnInspectorGUI();
            EditorGUILayout.EndVertical();
        }

      

     
     

       
        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            float baseHeight = base.GetPropertyHeight(property, label);
            return baseHeight;
        }
    }
}