// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace WPFMA
{
    /// <summary>Goes up whenever something in the open scenes changes, so a tool can keep a count until then.</summary>
    internal static class WPFMASceneStamp
    {
        internal static int Value { get; private set; }

        static WPFMASceneStamp()
        {
            EditorApplication.hierarchyChanged += () => Value++;
            Undo.undoRedoPerformed += () => Value++;
            ObjectChangeEvents.changesPublished += (ref ObjectChangeEventStream stream) => Value++;
        }
    }

    /// <summary>
    /// Removing things from an avatar in bulk: every component of a kind (PhysBones, colliders, particles, lights...),
    /// missing scripts, empty objects, or objects by name. Everything goes through Undo and the Change log.
    /// </summary>
    internal static class WPFMARemoval
    {
        internal sealed class Kind
        {
            public string Id;
            public string Label;
            public string Hint;
            /// <summary>Component types, in the order they're removed (a component that needs another goes first).</summary>
            public Type[] Types = new Type[0];
            /// <summary>For kinds that come from packages that may not be installed: types looked up by name.</summary>
            public string[] TypeNames = new string[0];
            public bool SkipRoot;
        }

        internal static readonly List<Kind> Kinds = BuildKinds();

        private static List<Kind> BuildKinds()
        {
            var kinds = new List<Kind>();
#if WPFMA_VRC_AVATARS
            kinds.Add(new Kind { Id = "physbones", Label = "PhysBones", Types = new[] { typeof(VRC.SDK3.Dynamics.PhysBone.Components.VRCPhysBone) } });
            kinds.Add(new Kind { Id = "pbcolliders", Label = "PhysBone colliders", Types = new[] { typeof(VRC.SDK3.Dynamics.PhysBone.Components.VRCPhysBoneCollider) } });
            kinds.Add(new Kind { Id = "contacts", Label = "Contacts (senders and receivers)", Types = new[] { typeof(VRC.Dynamics.ContactBase) } });
            kinds.Add(new Kind { Id = "vrcconstraints", Label = "VRChat constraints", Types = new[] { typeof(VRC.Dynamics.VRCConstraintBase) } });
#endif
            kinds.Add(new Kind { Id = "constraints", Label = "Unity constraints", Hint = "Aim, Look At, Parent, Position, Rotation and Scale", Types = new[] { typeof(UnityEngine.Animations.IConstraint) } });
            kinds.Add(new Kind { Id = "dynamicbones", Label = "Dynamic Bones (old)", Hint = "Replaced by PhysBones; VRChat ignores them",
                TypeNames = new[] { "DynamicBone", "DynamicBoneCollider", "DynamicBonePlaneCollider", "DynamicBoneColliderBase" } });
            kinds.Add(new Kind { Id = "particles", Label = "Particle systems", Types = new[] { typeof(ParticleSystem), typeof(ParticleSystemRenderer) } });
            kinds.Add(new Kind { Id = "trails", Label = "Trail and line renderers", Types = new[] { typeof(TrailRenderer), typeof(LineRenderer) } });
            kinds.Add(new Kind { Id = "lights", Label = "Lights", Types = new[] { typeof(Light) } });
            kinds.Add(new Kind { Id = "audio", Label = "Audio sources", TypeNames = new[] { "VRCSpatialAudioSource" }, Types = new[] { typeof(AudioSource) } });
            kinds.Add(new Kind { Id = "cloth", Label = "Cloth", Types = new[] { typeof(Cloth) } });
            kinds.Add(new Kind { Id = "rigidbodies", Label = "Rigidbodies and joints", Types = new[] { typeof(Joint), typeof(Rigidbody) } });
            kinds.Add(new Kind { Id = "colliders", Label = "Colliders", Hint = "Unity's physics colliders, not PhysBone colliders", Types = new[] { typeof(Collider) } });
            kinds.Add(new Kind { Id = "cameras", Label = "Cameras", Types = new[] { typeof(Camera) } });
            kinds.Add(new Kind { Id = "animators", Label = "Animators below the root", Hint = "The avatar's own Animator stays", Types = new[] { typeof(Animator) }, SkipRoot = true });
            return kinds;
        }

        // Looked up once per script reload (searching every assembly is slow).
        private static readonly Dictionary<string, Type> named = new Dictionary<string, Type>();

        private static IEnumerable<Type> TypesOf(Kind kind)
        {
            foreach (var name in kind.TypeNames)
            {
                Type found;
                if (!named.TryGetValue(name, out found))
                {
                    found = TypeCache.GetTypesDerivedFrom<Component>().FirstOrDefault(t => t.Name == name);
                    named[name] = found;
                }
                if (found != null)
                    yield return found;
            }
            foreach (var type in kind.Types)
                yield return type;
        }

        /// <summary>How many of each kind the avatar has, from one pass over its components.</summary>
        internal static Dictionary<string, int> CountAll(GameObject root)
        {
            var all = root.GetComponentsInChildren<Component>(true).Where(c => c != null).ToList();
            return Kinds.ToDictionary(k => k.Id, k => Find(all, root, k).Count);
        }

        /// <summary>The kind's components on the avatar, in the order they should go.</summary>
        internal static List<Component> Find(GameObject root, Kind kind)
        {
            return Find(root.GetComponentsInChildren<Component>(true).Where(c => c != null).ToList(), root, kind);
        }

        private static List<Component> Find(List<Component> all, GameObject root, Kind kind)
        {
            var found = new List<Component>();
            var seen = new HashSet<Component>();
            foreach (var type in TypesOf(kind))
                foreach (var c in all)
                    if (type.IsInstanceOfType(c) && !(kind.SkipRoot && c.gameObject == root) && seen.Add(c))
                        found.Add(c);
            return found;
        }

        /// <summary>Other components on the same object that need this one (Unity won't remove a component something needs).</summary>
        private static List<Component> Needing(Component component)
        {
            var needing = new List<Component>();
            foreach (var other in component.GetComponents<Component>())
            {
                if (other == null || other == component)
                    continue;
                foreach (RequireComponent require in other.GetType().GetCustomAttributes(typeof(RequireComponent), true))
                {
                    if ((require.m_Type0 != null && require.m_Type0.IsInstanceOfType(component)) ||
                        (require.m_Type1 != null && require.m_Type1.IsInstanceOfType(component)) ||
                        (require.m_Type2 != null && require.m_Type2.IsInstanceOfType(component)))
                    {
                        needing.Add(other);
                        break;
                    }
                }
            }
            return needing;
        }

        /// <summary>Removes components (with Undo), the ones that need others first. Returns removed and kept counts.</summary>
        internal static void RemoveComponents(List<Component> components, out int removed, out int kept)
        {
            removed = 0;
            kept = 0;
            var pending = components.Where(c => c != null).ToList();
            bool progress = true;
            while (pending.Count > 0 && progress)
            {
                progress = false;
                foreach (var component in pending.ToList())
                {
                    if (component == null)
                    {
                        pending.Remove(component);
                        continue;
                    }

                    var needing = Needing(component);
                    if (needing.Count == 0)
                    {
                        Undo.DestroyObjectImmediate(component);
                        pending.Remove(component);
                        removed++;
                        progress = true;
                    }
                    else if (!needing.Any(pending.Contains))
                    {
                        // Something staying on the object needs it, so it stays too.
                        pending.Remove(component);
                        kept++;
                        progress = true;
                    }
                }
            }
            kept += pending.Count;
        }

        // ---- Missing scripts ----------------------------------------------------------------------------------------

        internal static int MissingScripts(GameObject root)
        {
            return root.GetComponentsInChildren<Transform>(true).Sum(t => GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(t.gameObject));
        }

        internal static int RemoveMissingScripts(GameObject root)
        {
            int removed = 0;
            foreach (var t in root.GetComponentsInChildren<Transform>(true))
            {
                if (GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(t.gameObject) == 0)
                    continue;
                Undo.RegisterCompleteObjectUndo(t.gameObject, "Remove missing scripts");
                removed += GameObjectUtility.RemoveMonoBehavioursWithMissingScript(t.gameObject);
            }
            return removed;
        }

        // ---- Empty objects --------------------------------------------------------------------------------------------

        /// <summary>
        /// Objects with nothing on them and nothing below them that nothing uses: not a bone, not something a component
        /// or an animation points at. Removing one can leave its parent empty, so those go too.
        /// </summary>
        internal static List<GameObject> EmptyObjects(GameObject root)
        {
            var used = UsedTransforms(root);
            var empty = new List<GameObject>();
            var gone = new HashSet<Transform>();

            foreach (var t in root.GetComponentsInChildren<Transform>(true).OrderByDescending(Depth))
            {
                if (t == root.transform || used.Contains(t) || t.GetComponents<Component>().Length != 1)
                    continue;
                if (t.Cast<Transform>().Any(child => !gone.Contains(child)))
                    continue;
                if (PrefabUtility.IsPartOfPrefabInstance(t.gameObject) && !PrefabUtility.IsAddedGameObjectOverride(t.gameObject))
                    continue;
                empty.Add(t.gameObject);
                gone.Add(t);
            }
            return empty;
        }

        private static int Depth(Transform t)
        {
            int depth = 0;
            for (var p = t.parent; p != null; p = p.parent)
                depth++;
            return depth;
        }

        /// <summary>Transforms the avatar needs: bones, humanoid bones, anything a component or an animation points at.</summary>
        internal static HashSet<Transform> UsedTransforms(GameObject root)
        {
            var used = new HashSet<Transform> { root.transform };

            foreach (var skinned in root.GetComponentsInChildren<SkinnedMeshRenderer>(true))
            {
                if (skinned.rootBone != null)
                    used.Add(skinned.rootBone);
                foreach (var bone in skinned.bones)
                    if (bone != null)
                        used.Add(bone);
            }

            var animator = root.GetComponent<Animator>();
            if (animator != null && animator.isHuman)
                foreach (HumanBodyBones bone in Enum.GetValues(typeof(HumanBodyBones)))
                    if (bone != HumanBodyBones.LastBone && animator.GetBoneTransform(bone) != null)
                        used.Add(animator.GetBoneTransform(bone));

            foreach (var component in root.GetComponentsInChildren<Component>(true))
            {
                if (component == null || component is Transform)
                    continue;

                // PhysBones and Dynamic Bones move every bone below their root without pointing at each one, and an
                // end bone with nothing on it still shapes the chain, so the whole chain counts as used.
                string type = component.GetType().Name;
                if (type == "VRCPhysBone" || type == "DynamicBone")
                {
                    var start = new SerializedObject(component).FindProperty(type == "VRCPhysBone" ? "rootTransform" : "m_Root");
                    var chainRoot = start != null ? start.objectReferenceValue as Transform : null;
                    foreach (var t in (chainRoot != null ? chainRoot : component.transform).GetComponentsInChildren<Transform>(true))
                        used.Add(t);
                }

                var property = new SerializedObject(component).GetIterator();
                int guard = 0;
                while (property.Next(true) && guard++ < 20000)
                {
                    if (property.propertyType != SerializedPropertyType.ObjectReference || property.objectReferenceValue == null)
                        continue;
                    var go = property.objectReferenceValue as GameObject;
                    var t = go != null ? go.transform : property.objectReferenceValue as Transform;
                    if (t == null)
                    {
                        var other = property.objectReferenceValue as Component;
                        t = other != null && other.gameObject != component.gameObject ? other.transform : null;
                    }
                    if (t != null && t.IsChildOf(root.transform))
                        used.Add(t);
                }
            }

            foreach (var source in WPFMAAvatarAnimations.Sources(root, true))
                foreach (var clip in source.Clips)
                    foreach (var binding in AnimationUtility.GetCurveBindings(clip).Concat(AnimationUtility.GetObjectReferenceCurveBindings(clip)))
                    {
                        var t = source.Base.Find(binding.path);
                        for (; t != null && t != source.Base; t = t.parent)
                            used.Add(t);
                    }

            return used;
        }

        internal static int RemoveObjects(IEnumerable<GameObject> objects)
        {
            int removed = 0;
            foreach (var go in objects.ToList())
            {
                if (go == null)
                    continue;
                Undo.DestroyObjectImmediate(go);
                removed++;
            }
            return removed;
        }

        // ---- By name --------------------------------------------------------------------------------------------------

        internal enum Match
        {
            Contains,
            Exactly,
            StartsWith
        }

        internal sealed class NameMatches
        {
            public readonly List<GameObject> Remove = new List<GameObject>();
            public readonly List<GameObject> Bones = new List<GameObject>();
            public readonly List<GameObject> InPrefab = new List<GameObject>();
        }

        /// <summary>
        /// Objects whose name matches (only the top one of a matching branch; its children go with it). Objects that
        /// hold bones a mesh elsewhere uses, or humanoid bones, are kept - removing them would break the avatar.
        /// </summary>
        internal static NameMatches ByName(GameObject root, string text, Match match, bool editorOnly)
        {
            var result = new NameMatches();
            if (root == null || (string.IsNullOrEmpty(text) && !editorOnly))
                return result;

            Func<string, bool> matches = name =>
            {
                if (string.IsNullOrEmpty(text))
                    return false;
                switch (match)
                {
                    case Match.Exactly: return string.Equals(name, text, StringComparison.OrdinalIgnoreCase);
                    case Match.StartsWith: return name.StartsWith(text, StringComparison.OrdinalIgnoreCase);
                    default: return name.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0;
                }
            };

            var animator = root.GetComponent<Animator>();
            var human = new HashSet<Transform>();
            if (animator != null && animator.isHuman)
                foreach (HumanBodyBones bone in Enum.GetValues(typeof(HumanBodyBones)))
                    if (bone != HumanBodyBones.LastBone && animator.GetBoneTransform(bone) != null)
                        human.Add(animator.GetBoneTransform(bone));
            var skinned = root.GetComponentsInChildren<SkinnedMeshRenderer>(true);

            foreach (var t in root.GetComponentsInChildren<Transform>(true).OrderBy(Depth))
            {
                if (t == root.transform || !(matches(t.name) || (editorOnly && t.CompareTag("EditorOnly"))))
                    continue;
                if (result.Remove.Concat(result.Bones).Concat(result.InPrefab).Any(g => t.IsChildOf(g.transform)))
                    continue;

                bool holdsBones = human.Any(h => h.IsChildOf(t)) ||
                                  skinned.Any(s => !s.transform.IsChildOf(t) &&
                                                   ((s.rootBone != null && s.rootBone.IsChildOf(t)) || s.bones.Any(b => b != null && b.IsChildOf(t))));
                if (holdsBones)
                    result.Bones.Add(t.gameObject);
                else if (PrefabUtility.IsPartOfPrefabInstance(t.gameObject) && !PrefabUtility.IsAddedGameObjectOverride(t.gameObject))
                    result.InPrefab.Add(t.gameObject);
                else
                    result.Remove.Add(t.gameObject);
            }
            return result;
        }
    }

    internal static class WPFMARemovalSection
    {
        private const string PrefKey = "WPFMA.Tools.RemovalExpanded";
        private static readonly HashSet<string> ticked = new HashSet<string>();
        private static bool tickMissing, tickEmpty;
        private static GameObject countedFor;
        private static int countedAt = -1;
        private static Dictionary<string, int> counts;
        private static int missing, empty;
        private static string status;

        internal static void Draw(GUIStyle sectionStyle)
        {
            if (!WPFMAToolSection.AvatarProject)
                return;
            WPFMAToolSection.Draw(sectionStyle, "Removal", Detail(), PrefKey, Body);
        }

        private static string Detail()
        {
            return ticked.Count + (tickMissing ? 1 : 0) + (tickEmpty ? 1 : 0) == 0 ? "nothing ticked" : "ready to remove";
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Remove components in bulk.", "Removes every component of a kind from the avatar in one go, plus missing scripts and empty objects. " + "Tick what should go. Undo puts it all back."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            var root = WPFMAAvatarFolders.AvatarRoot(Selection.activeGameObject);
            if (root == null)
            {
                EditorGUILayout.LabelField("Select the avatar in the Hierarchy.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

            // Counted again when the avatar or the scene changes, not every frame.
            int stamp = WPFMASceneStamp.Value;
            if (counts == null || countedFor != root || countedAt != stamp)
            {
                countedFor = root;
                countedAt = stamp;
                counts = WPFMARemoval.CountAll(root);
                missing = WPFMARemoval.MissingScripts(root);
                empty = -1;
            }

            EditorGUILayout.LabelField("Avatar", root.name, EditorStyles.boldLabel);
            foreach (var kind in WPFMARemoval.Kinds)
            {
                int count = counts[kind.Id];
                using (new EditorGUI.DisabledScope(count == 0))
                {
                    bool on = ticked.Contains(kind.Id) && count > 0;
                    bool now = EditorGUILayout.ToggleLeft(new GUIContent(kind.Label + "  (" + count + ")", kind.Hint), on);
                    if (now != on)
                    {
                        if (now)
                            ticked.Add(kind.Id);
                        else
                            ticked.Remove(kind.Id);
                    }
                }
            }

            using (new EditorGUI.DisabledScope(missing == 0))
                tickMissing = EditorGUILayout.ToggleLeft("Missing scripts  (" + missing + ")", tickMissing && missing > 0);

            using (new EditorGUILayout.HorizontalScope())
            {
                string emptyLabel = empty < 0 ? "Empty objects  (not counted yet)" : "Empty objects  (" + empty + ")";
                tickEmpty = EditorGUILayout.ToggleLeft(new GUIContent(emptyLabel,
                    "Objects with nothing on them and nothing below them that aren't bones and nothing points at."), tickEmpty && empty != 0);
                if (empty < 0 && GUILayout.Button("Count", EditorStyles.miniButton, GUILayout.Width(60f)))
                    empty = WPFMARemoval.EmptyObjects(root).Count;
            }

            EditorGUILayout.Space(4f);
            bool any = ticked.Count > 0 || tickMissing || tickEmpty;
            using (new EditorGUI.DisabledScope(!any))
            {
                if (GUILayout.Button("Remove ticked", GUILayout.Height(26f)))
                {
                    var target = root;
                    var kinds = WPFMARemoval.Kinds.Where(k => ticked.Contains(k.Id)).ToList();
                    bool scripts = tickMissing, objects = tickEmpty;
                    EditorApplication.delayCall += () =>
                    {
                        status = WPFMAChangeLog.Run("Removal", "Remove from '" + target.name + "'", null, true, () => Remove(target, kinds, scripts, objects));
                        Debug.Log("[WPFMA-SDK] " + status);
                        counts = null;
                    };
                }
            }

            if (!string.IsNullOrEmpty(status))
                EditorGUILayout.LabelField(status, WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
        }

        internal static string Remove(GameObject root, List<WPFMARemoval.Kind> kinds, bool scripts, bool objects)
        {
            Undo.SetCurrentGroupName("Remove from avatar");
            int group = Undo.GetCurrentGroup();
            var done = new List<string>();
            int keptTotal = 0;

            if (scripts)
            {
                int n = WPFMARemoval.RemoveMissingScripts(root);
                if (n > 0)
                    done.Add(n + " missing script(s)");
            }

            foreach (var kind in kinds)
            {
                int removed, kept;
                WPFMARemoval.RemoveComponents(WPFMARemoval.Find(root, kind), out removed, out kept);
                if (removed > 0)
                    done.Add(removed + " " + kind.Label.ToLowerInvariant());
                keptTotal += kept;
            }

            if (objects)
            {
                int n = WPFMARemoval.RemoveObjects(WPFMARemoval.EmptyObjects(root));
                if (n > 0)
                    done.Add(n + " empty object(s)");
            }

            Undo.CollapseUndoOperations(group);
            return (done.Count == 0 ? "Nothing to remove." : "Removed " + string.Join(", ", done.ToArray()) + ".") +
                   (keptTotal > 0 ? " Kept " + keptTotal + " that other components on the same object need." : string.Empty);
        }
    }

    internal static class WPFMARemoveByNameSection
    {
        private const string PrefKey = "WPFMA.Tools.RemoveByNameExpanded";
        private static string text = string.Empty;
        private static WPFMARemoval.Match match;
        private static bool editorOnly;
        private static string status;
        private static Vector2 scroll;
        private static WPFMARemoval.NameMatches found;
        private static string foundKey;

        internal static void Draw(GUIStyle sectionStyle)
        {
            if (!WPFMAToolSection.AvatarProject)
                return;
            WPFMAToolSection.Draw(sectionStyle, "Remove by name", string.IsNullOrEmpty(text) ? "type a name" : "'" + text + "'", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Remove objects by name.", "Removes objects whose name matches, like every 'Dynamic Bone' helper or old 'Armature.001'. You see the list " + "first. Objects holding bones a mesh uses are kept."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            var root = WPFMAAvatarFolders.AvatarRoot(Selection.activeGameObject);
            if (root == null)
            {
                EditorGUILayout.LabelField("Select the avatar in the Hierarchy.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                match = (WPFMARemoval.Match)EditorGUILayout.EnumPopup(match, GUILayout.Width(100f));
                text = EditorGUILayout.TextField(text);
            }
            editorOnly = EditorGUILayout.ToggleLeft("Also objects tagged EditorOnly", editorOnly);

            // Searched again when the text, the avatar or the scene changes, not on every repaint.
            string key = root.GetInstanceID() + "|" + text.Trim() + "|" + match + "|" + editorOnly + "|" + WPFMASceneStamp.Value;
            if (found == null || key != foundKey)
            {
                found = WPFMARemoval.ByName(root, text.Trim(), match, editorOnly);
                foundKey = key;
            }
            if (found.Remove.Count + found.Bones.Count + found.InPrefab.Count == 0)
            {
                if (!string.IsNullOrEmpty(text.Trim()) || editorOnly)
                    EditorGUILayout.LabelField("Nothing on '" + root.name + "' matches.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            }
            else
            {
                scroll = EditorGUILayout.BeginScrollView(scroll, GUILayout.MaxHeight(160f));
                foreach (var go in found.Remove)
                    Row(go, root, null);
                foreach (var go in found.Bones)
                    Row(go, root, "kept: holds bones");
                foreach (var go in found.InPrefab)
                    Row(go, root, "kept: part of a prefab");
                EditorGUILayout.EndScrollView();

                if (found.InPrefab.Count > 0)
                    EditorGUILayout.LabelField(new GUIContent("Prefab parts can't be removed here.", "Objects that are part of a prefab can't be removed from here. Unpack the prefab first, or remove them in the prefab."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            }

            using (new EditorGUI.DisabledScope(found.Remove.Count == 0))
            {
                if (GUILayout.Button("Remove " + found.Remove.Count + " object(s)", GUILayout.Height(26f)))
                {
                    var list = found.Remove.ToList();
                    var target = root;
                    EditorApplication.delayCall += () =>
                    {
                        if (!EditorUtility.DisplayDialog("Remove " + list.Count + " object(s)?",
                                string.Join("\n", list.Take(12).Select(g => g.name).ToArray()) + (list.Count > 12 ? "\n..." : string.Empty) +
                                "\n\nTheir children go with them. Undo puts them back.", "Remove", "Cancel"))
                            return;
                        status = WPFMAChangeLog.Run("Remove by name", "Remove " + list.Count + " object(s) from '" + target.name + "'", null, true, () =>
                        {
                            Undo.SetCurrentGroupName("Remove by name");
                            int group = Undo.GetCurrentGroup();
                            int n = WPFMARemoval.RemoveObjects(list);
                            Undo.CollapseUndoOperations(group);
                            return "Removed " + n + " object(s).";
                        });
                        Debug.Log("[WPFMA-SDK] Remove by name: " + status);
                    };
                }
            }

            if (!string.IsNullOrEmpty(status))
                EditorGUILayout.LabelField(status, WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
        }

        private static void Row(GameObject go, GameObject root, string note)
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField(new GUIContent(AnimationUtility.CalculateTransformPath(go.transform, root.transform)),
                    WPFMAToolSection.Hint(note == null ? WPFMAToolSection.MetaText : WPFMAToolSection.FaintText));
                if (note != null)
                    EditorGUILayout.LabelField(note, WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber), GUILayout.Width(130f));
                if (GUILayout.Button("Show", EditorStyles.miniButton, GUILayout.Width(44f)))
                    EditorGUIUtility.PingObject(go);
            }
        }
    }
}
#endif
