using System;
using System.Reflection;
using UnityEditor;
using UnityEditor.Rendering;
using UnityEngine;

[CustomEditor(typeof(Transform), true)]
public class TransformExtensionEditor : Editor
{
    Editor defaultEditor;
    Transform transform;

    void OnEnable()
    {
        //When this inspector is created, also create the built-in inspector
        defaultEditor = CreateEditor(targets, Type.GetType("UnityEditor.TransformInspector, UnityEditor"));
        transform = target as Transform;
    }

    void OnDisable()
    {
        //When OnDisable is called, the default editor we created should be destroyed to avoid memory leakage.
        //Also, make sure to call any required methods like OnDisable
        MethodInfo disableMethod = defaultEditor.GetType().GetMethod("OnDisable", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
        if (disableMethod != null)
            disableMethod.Invoke(defaultEditor, null);
        DestroyImmediate(defaultEditor);
    }

    public override void OnInspectorGUI()
    {
        EditorGUILayout.LabelField("Local Space", EditorStyles.boldLabel);
        defaultEditor.OnInspectorGUI();

        Transform sceneCameraTransform = SceneView.lastActiveSceneView.camera.transform;

        if (GUILayout.Button("Set at View Point"))
        {
            transform.position = sceneCameraTransform.position;
            transform.rotation = sceneCameraTransform.rotation;
        }
        if (GUILayout.Button("Set SceneCamera to selected"))
        {
            sceneCameraTransform.position = transform.position;
            sceneCameraTransform.rotation = transform.rotation;

            SceneView.lastActiveSceneView.rotation = transform.rotation;
            SceneView.lastActiveSceneView.AlignViewToObject(transform);
        }
    }
}
