// 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
{
    internal static class WPFMAComponentCopier
    {
        internal enum Category
        {
            Descriptor,
            Dynamics,
            ModularAvatar,
            VRCFury,
            Unity,
            Other
        }

        internal sealed class Options
        {
            public GameObject From;
            public GameObject To;
            public readonly HashSet<Category> Categories = new HashSet<Category>
            {
                Category.Descriptor, Category.Dynamics, Category.ModularAvatar, Category.VRCFury, Category.Unity
            };
            public bool Overwrite = true;
            public bool CreateMissingObjects = true;
        }

        internal sealed class Plan
        {
            public readonly Dictionary<Category, int> Counts = new Dictionary<Category, int>();
            public int MissingTargets;
            public int NewObjects;
            public readonly List<string> MissingPaths = new List<string>();
        }

        internal sealed class Result
        {
            public int Added;
            public int Overwritten;
            public int Skipped;
            public int CreatedObjects;
            public readonly List<string> Notes = new List<string>();
        }

        private static readonly Type[] NeverCopied =
        {
            typeof(Transform), typeof(Animator), typeof(SkinnedMeshRenderer), typeof(MeshRenderer), typeof(MeshFilter)
        };

        internal static Category? Classify(Component component)
        {
            if (component == null)
                return null;

            var type = component.GetType();
            if (NeverCopied.Any(t => t == type) || type.Name == "PipelineManager")
                return null;

            string ns = type.Namespace ?? string.Empty;

            if (type.Name == "VRCAvatarDescriptor")
                return Category.Descriptor;
            if (ns.StartsWith("VRC"))
                return Category.Dynamics;
            if (ns.StartsWith("nadena.dev"))
                return Category.ModularAvatar;
            if (ns.StartsWith("VF") || type.Name.StartsWith("VRCFury"))
                return Category.VRCFury;
            if (ns.StartsWith("UnityEngine"))
                return type == typeof(ParticleSystem) || type == typeof(ParticleSystemRenderer) ? (Category?)null : Category.Unity;

            return Category.Other;
        }

        internal static string Label(Category category)
        {
            switch (category)
            {
                case Category.Descriptor: return "Avatar Descriptor settings";
                case Category.Dynamics: return "VRChat components (PhysBones, contacts, constraints...)";
                case Category.ModularAvatar: return "Modular Avatar components";
                case Category.VRCFury: return "VRCFury components";
                case Category.Unity: return "Unity components (constraints, audio, lights...)";
                default: return "Other scripts";
            }
        }

        internal static Plan Preview(Options options)
        {
            var plan = new Plan();
            if (options.From == null || options.To == null)
                return plan;

            var lookup = Lookup(options.To.transform);

            foreach (var source in options.From.GetComponentsInChildren<Transform>(true))
            {
                var components = source.GetComponents<Component>()
                    .Select(c => new { Component = c, Category = Classify(c) })
                    .Where(c => c.Category.HasValue && options.Categories.Contains(c.Category.Value))
                    .ToList();

                if (components.Count == 0)
                    continue;

                bool exists = Counterpart(options.From.transform, options.To.transform, source, lookup) != null;
                if (!exists)
                {
                    if (options.CreateMissingObjects && CanCreate(options, source, lookup))
                    {
                        plan.NewObjects++;
                    }
                    else
                    {
                        plan.MissingTargets += components.Count;
                        plan.MissingPaths.Add(AnimationUtility.CalculateTransformPath(source, options.From.transform));
                        continue;
                    }
                }

                foreach (var item in components)
                {
                    int count;
                    plan.Counts.TryGetValue(item.Category.Value, out count);
                    plan.Counts[item.Category.Value] = count + 1;
                }
            }

            return plan;
        }

        internal static Result Copy(Options options)
        {
            var result = new Result();
            var fromRoot = options.From.transform;
            var toRoot = options.To.transform;

            Undo.SetCurrentGroupName("Copy components");
            int group = Undo.GetCurrentGroup();

            var lookup = Lookup(toRoot);
            var objectMap = new Dictionary<GameObject, GameObject>();
            var componentMap = new Dictionary<Component, Component>();
            var pairs = new List<KeyValuePair<Component, Component>>();

            foreach (var source in fromRoot.GetComponentsInChildren<Transform>(true).OrderBy(t => Depth(t)))
            {
                var target = Counterpart(fromRoot, toRoot, source, lookup);
                if (target != null)
                    objectMap[source.gameObject] = target.gameObject;
            }

            foreach (var source in fromRoot.GetComponentsInChildren<Transform>(true).OrderBy(t => Depth(t)))
            {
                var wanted = source.GetComponents<Component>()
                    .Where(c => { var k = Classify(c); return k.HasValue && options.Categories.Contains(k.Value); })
                    .ToList();

                if (wanted.Count == 0)
                    continue;

                GameObject target;
                if (!objectMap.TryGetValue(source.gameObject, out target))
                {
                    if (!options.CreateMissingObjects || !CanCreate(options, source, lookup))
                    {
                        result.Skipped += wanted.Count;
                        continue;
                    }

                    target = CreateCounterpart(source, objectMap);
                    if (target == null)
                    {
                        result.Skipped += wanted.Count;
                        continue;
                    }

                    result.CreatedObjects++;
                }

                var sameTypeIndex = new Dictionary<Type, int>();
                foreach (var component in wanted)
                {
                    var type = component.GetType();
                    int index;
                    sameTypeIndex.TryGetValue(type, out index);
                    sameTypeIndex[type] = index + 1;

                    var existing = target.GetComponents(type);
                    Component destination;

                    if (index < existing.Length)
                    {
                        if (!options.Overwrite)
                        {
                            result.Skipped++;
                            continue;
                        }

                        destination = existing[index];
                        Undo.RecordObject(destination, "Copy components");
                        result.Overwritten++;
                    }
                    else
                    {
                        destination = Undo.AddComponent(target, type);
                        if (destination == null)
                        {
                            result.Skipped++;
                            continue;
                        }

                        result.Added++;
                    }

                    componentMap[component] = destination;
                    pairs.Add(new KeyValuePair<Component, Component>(component, destination));
                }
            }

            foreach (var pair in pairs)
            {
                EditorUtility.CopySerialized(pair.Key, pair.Value);
                Remap(pair.Value, fromRoot, objectMap, componentMap);
                PrefabUtility.RecordPrefabInstancePropertyModifications(pair.Value);
            }

            Undo.CollapseUndoOperations(group);

            if (result.Skipped > 0)
                result.Notes.Add(result.Skipped + " component(s) skipped because their object is not in the new avatar, or already had one.");

            return result;
        }

        private static void Remap(Component component, Transform fromRoot,
            Dictionary<GameObject, GameObject> objectMap, Dictionary<Component, Component> componentMap)
        {
            var serialized = new SerializedObject(component);
            var property = serialized.GetIterator();
            bool changed = false;

            while (property.Next(true))
            {
                if (property.propertyType != SerializedPropertyType.ObjectReference ||
                    property.name == "m_GameObject" || property.name == "m_Script")
                    continue;

                var value = property.objectReferenceValue;
                if (value == null)
                    continue;

                var mapped = MapReference(value, fromRoot, objectMap, componentMap);
                if (mapped == value)
                    continue;

                property.objectReferenceValue = mapped;
                changed = true;
            }

            if (changed)
                serialized.ApplyModifiedPropertiesWithoutUndo();
        }

        private static UnityEngine.Object MapReference(UnityEngine.Object value, Transform fromRoot,
            Dictionary<GameObject, GameObject> objectMap, Dictionary<Component, Component> componentMap)
        {
            var gameObject = value as GameObject;
            if (gameObject != null)
            {
                if (!gameObject.transform.IsChildOf(fromRoot))
                    return value;

                GameObject mapped;
                return objectMap.TryGetValue(gameObject, out mapped) ? mapped : null;
            }

            var component = value as Component;
            if (component == null || !component.transform.IsChildOf(fromRoot))
                return value;

            Component copied;
            if (componentMap.TryGetValue(component, out copied))
                return copied;

            GameObject target;
            if (!objectMap.TryGetValue(component.gameObject, out target))
                return null;

            if (component is Transform)
                return target.transform;

            var sources = component.gameObject.GetComponents(component.GetType());
            var targets = target.GetComponents(component.GetType());
            int index = Array.IndexOf(sources, component);
            return index >= 0 && index < targets.Length ? targets[index] : null;
        }

        private static Dictionary<string, List<Transform>> Lookup(Transform root)
        {
            var lookup = new Dictionary<string, List<Transform>>();
            foreach (var transform in root.GetComponentsInChildren<Transform>(true))
            {
                List<Transform> list;
                if (!lookup.TryGetValue(transform.name, out list))
                {
                    list = new List<Transform>();
                    lookup.Add(transform.name, list);
                }
                list.Add(transform);
            }
            return lookup;
        }

        private static Transform Counterpart(Transform fromRoot, Transform toRoot, Transform source,
            Dictionary<string, List<Transform>> lookup)
        {
            if (source == fromRoot)
                return toRoot;

            string path = AnimationUtility.CalculateTransformPath(source, fromRoot);
            var byPath = toRoot.Find(path);
            if (byPath != null)
                return byPath;

            List<Transform> sameName;
            return lookup.TryGetValue(source.name, out sameName) && sameName.Count == 1 ? sameName[0] : null;
        }

        private static bool CanCreate(Options options, Transform source, Dictionary<string, List<Transform>> lookup)
        {
            if (source.GetComponent<Renderer>() != null)
                return false;

            var parent = source.parent;
            while (parent != null)
            {
                if (Counterpart(options.From.transform, options.To.transform, parent, lookup) != null)
                    return true;
                parent = parent.parent;
            }

            return false;
        }

        private static GameObject CreateCounterpart(Transform source, Dictionary<GameObject, GameObject> objectMap)
        {
            var parent = source.parent;
            GameObject mappedParent = null;
            if (parent != null && !objectMap.TryGetValue(parent.gameObject, out mappedParent))
            {
                mappedParent = CreateCounterpart(parent, objectMap);
                if (mappedParent == null)
                    return null;
            }

            if (mappedParent == null)
                return null;

            var created = new GameObject(source.name);
            Undo.RegisterCreatedObjectUndo(created, "Copy components");
            created.transform.SetParent(mappedParent.transform, false);
            created.transform.localPosition = source.localPosition;
            created.transform.localRotation = source.localRotation;
            created.transform.localScale = source.localScale;
            created.SetActive(source.gameObject.activeSelf);
            created.tag = source.tag;
            created.layer = source.gameObject.layer;

            objectMap[source.gameObject] = created;
            return created;
        }

        private static int Depth(Transform transform)
        {
            int depth = 0;
            while (transform.parent != null)
            {
                depth++;
                transform = transform.parent;
            }
            return depth;
        }
    }

    internal static class WPFMAComponentCopierSection
    {
        private const string PrefKey = "WPFMA.Tools.ComponentCopierExpanded";

        private static readonly WPFMAComponentCopier.Options Options = new WPFMAComponentCopier.Options();
        private static string status;
        private static List<string> notes = new List<string>();
        private static WPFMAComponentCopier.Plan cachedPlan;
        private static string cachedKey;
        private static bool hierarchyHooked;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Component copier", Detail(), PrefKey, Body);
        }

        private static string Detail()
        {
            return Options.From != null && Options.To != null ? Options.From.name + " → " + Options.To.name : "pick two avatars";
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Copy components between avatars.", "Copies PhysBones, contacts, constraints, the descriptor's settings and Modular Avatar / VRCFury " + "components from one avatar to another - for example from your old setup onto a re-exported FBX. " + "Bones are matched by name, and references are pointed at the new avatar's own bones."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            Options.From = SceneObject("Copy from", Options.From);
            Options.To = SceneObject("Copy to", Options.To);

            if (Options.From != null && Options.To != null && Options.From == Options.To)
            {
                EditorGUILayout.LabelField("Pick two different avatars.", WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
                return;
            }

            if (Options.From != null && Options.To != null &&
                (Options.To.transform.IsChildOf(Options.From.transform) || Options.From.transform.IsChildOf(Options.To.transform)))
            {
                EditorGUILayout.LabelField("One avatar is inside the other. Pick two separate avatars.",
                    WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
                return;
            }

            EditorGUILayout.Space(4f);
            var plan = CurrentPlan();

            foreach (WPFMAComponentCopier.Category category in Enum.GetValues(typeof(WPFMAComponentCopier.Category)))
            {
                int count;
                plan.Counts.TryGetValue(category, out count);

                bool on = Options.Categories.Contains(category);
                bool now = EditorGUILayout.ToggleLeft(WPFMAComponentCopier.Label(category) + (Options.From != null ? "  (" + count + ")" : string.Empty), on);
                if (now && !on)
                    Options.Categories.Add(category);
                else if (!now && on)
                    Options.Categories.Remove(category);
            }

            EditorGUILayout.Space(2f);
            Options.Overwrite = WPFMAToolDefaults.CopierOverwrite =
                EditorGUILayout.ToggleLeft("Overwrite components the new avatar already has", WPFMAToolDefaults.CopierOverwrite);
            Options.CreateMissingObjects = WPFMAToolDefaults.CopierCreateMissing = EditorGUILayout.ToggleLeft(
                "Create empty objects that only exist on the old avatar (contact points, helpers)", WPFMAToolDefaults.CopierCreateMissing);

            if (Options.From != null && Options.To != null)
            {
                if (plan.NewObjects > 0)
                    EditorGUILayout.LabelField(plan.NewObjects + " empty object(s) will be created.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

                if (plan.MissingTargets > 0)
                {
                    EditorGUILayout.LabelField(
                        plan.MissingTargets + " component(s) will be skipped - their bone is not in the new avatar: " +
                        string.Join(", ", plan.MissingPaths.Take(5).ToArray()) + (plan.MissingPaths.Count > 5 ? "..." : string.Empty),
                        WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
                }

                EditorGUILayout.LabelField(new GUIContent("The upload ID is never copied.", "The Pipeline Manager (upload ID) is never copied, so the new avatar keeps its own."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            }

            EditorGUILayout.Space(4f);
            using (new EditorGUI.DisabledScope(Options.From == null || Options.To == null || plan.Counts.Values.Sum() == 0))
            {
                if (GUILayout.Button("Copy " + plan.Counts.Values.Sum() + " component(s)", GUILayout.Height(26f)))
                {
                    EditorApplication.delayCall += () => WPFMAChangeLog.Run("Component copier",
                        "Copy from '" + Options.From.name + "' to '" + Options.To.name + "'", null, true, () =>
                    {
                        var result = WPFMAComponentCopier.Copy(Options);
                        status = "Added " + result.Added + ", overwrote " + result.Overwritten +
                                 (result.CreatedObjects > 0 ? ", created " + result.CreatedObjects + " object(s)" : string.Empty) +
                                 ". Ctrl+Z undoes it all.";
                        notes = result.Notes;
                        Debug.Log("[WPFMA-SDK] Component copier: " + status);
                        return status;
                    });
                }
            }

            if (!string.IsNullOrEmpty(status))
                EditorGUILayout.LabelField(status, WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
            foreach (var note in notes)
                EditorGUILayout.LabelField(note, WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
        }

        private static WPFMAComponentCopier.Plan CurrentPlan()
        {
            if (!hierarchyHooked)
            {
                EditorApplication.hierarchyChanged += () => cachedKey = null;
                Undo.undoRedoPerformed += () => cachedKey = null;
                hierarchyHooked = true;
            }

            string key = (Options.From != null ? Options.From.GetInstanceID() : 0) + "|" +
                         (Options.To != null ? Options.To.GetInstanceID() : 0) + "|" +
                         string.Join(",", Options.Categories.Select(c => ((int)c).ToString()).OrderBy(s => s).ToArray()) + "|" +
                         Options.CreateMissingObjects;

            if (key != cachedKey || cachedPlan == null)
            {
                cachedPlan = WPFMAComponentCopier.Preview(Options);
                cachedKey = key;
            }

            return cachedPlan;
        }

        private static GameObject SceneObject(string label, GameObject current)
        {
            var picked = (GameObject)EditorGUILayout.ObjectField(label, current, typeof(GameObject), true);
            return picked != null && EditorUtility.IsPersistent(picked) ? current : picked;
        }
    }
}
#endif
