﻿#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Arugula.Animation;

[CustomPropertyDrawer(typeof(TransformPose))]
public class TransformPoseDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.PropertyField(position, property, true);

        Rect contextRect = position;
        contextRect.height = EditorGUIUtility.singleLineHeight;
        Event ev = Event.current;
        if (ev.type == EventType.MouseUp && ev.button > 0)
        {
            if (contextRect.Contains(ev.mousePosition))
            {
                if (property.serializedObject.targetObject is Component)
                {
                    DefaultsContextMenu(property);
                    ev.Use();
                }
            }
        }
    }



    void DefaultsContextMenu(SerializedProperty property)
    {
        Transform t = ((Component)property.serializedObject.targetObject).transform;

        SerializedProperty position = property.FindPropertyRelative("position");
        SerializedProperty rotation = property.FindPropertyRelative("rotation");
        SerializedProperty scale = property.FindPropertyRelative("scale");
        SerializedProperty space = property.FindPropertyRelative("space");

        GenericMenu menu = new GenericMenu();

        menu.AddItem(new GUIContent("Copy Self"), false, () =>
        {
            position.vector3Value = t.localPosition;
            rotation.quaternionValue = t.localRotation;
            scale.vector3Value = t.localScale;
            space.enumValueIndex = (int)Space.Self;
            property.serializedObject.ApplyModifiedProperties();
        });

        menu.AddItem(new GUIContent("Copy World"), false, () =>
        {
            position.vector3Value = t.position;
            rotation.quaternionValue = t.rotation;
            scale.vector3Value = t.lossyScale;
            space.enumValueIndex = (int)Space.World;
            property.serializedObject.ApplyModifiedProperties();
        });

        menu.AddSeparator("");

        menu.AddItem(new GUIContent("Apply"), false, () =>
        {
            if (space.enumValueIndex == (int)Space.Self)
            {
                t.localPosition = position.vector3Value;
                t.localRotation = rotation.quaternionValue;
                t.localScale = scale.vector3Value;
            }
            else
            {
                t.position = position.vector3Value;
                t.rotation = rotation.quaternionValue;
                t.localScale = scale.vector3Value;
            }

            SceneView.RepaintAll();
        });



        menu.ShowAsContext();
    }


    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        return EditorGUI.GetPropertyHeight(property);
    }
}
#endif