// 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 UnityEditor.SceneManagement;
using UnityEngine;

namespace WPFMA
{
    /// <summary>
    /// Every reference that shows "Missing" (it pointed at something that was deleted), every missing script and every
    /// prefab whose asset is gone - in the open scenes, or in the project's prefabs, materials and other assets.
    /// </summary>
    internal static class WPFMAMissingReferences
    {
        internal sealed class Item
        {
            /// <summary>The component or asset holding the reference (null for a missing script).</summary>
            public UnityEngine.Object Owner;
            public GameObject GameObject;
            public UnityEngine.Object Asset;
            public string Where;
            public string What;
            public string Property;
            public bool Script;
            public bool InScene;
        }

        // Unity's own bookkeeping links: empty on purpose, not broken.
        private static readonly HashSet<string> Ignored = new HashSet<string>
        {
            "m_PrefabInstance", "m_PrefabAsset", "m_CorrespondingSourceObject", "m_GameObject", "m_Father", "m_Script"
        };

        internal static List<Item> ScanScenes()
        {
            var items = new List<Item>();
            for (int i = 0; i < EditorSceneManager.sceneCount; i++)
            {
                var scene = EditorSceneManager.GetSceneAt(i);
                if (!scene.isLoaded)
                    continue;
                foreach (var root in scene.GetRootGameObjects())
                    foreach (var t in root.GetComponentsInChildren<Transform>(true))
                        CheckObject(t.gameObject, scene.name + " > " + Path(t), true, null, items);
            }
            return items;
        }

        /// <summary>Prefabs, materials, controllers and other assets under Assets. Returns null if cancelled.</summary>
        internal static List<Item> ScanProject()
        {
            var items = new List<Item>();
            var guids = AssetDatabase.FindAssets("t:Prefab t:Material t:ScriptableObject t:AnimatorController", new[] { "Assets" });
            try
            {
                for (int i = 0; i < guids.Length; i++)
                {
                    string path = AssetDatabase.GUIDToAssetPath(guids[i]);
                    if (EditorUtility.DisplayCancelableProgressBar("Missing references", path, i / (float)Math.Max(1, guids.Length)))
                        return null;

                    if (path.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase))
                    {
                        var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
                        if (prefab != null)
                            foreach (var t in prefab.GetComponentsInChildren<Transform>(true))
                                CheckObject(t.gameObject, path + " > " + Path(t), false, prefab, items);
                    }
                    else
                    {
                        foreach (var asset in AssetDatabase.LoadAllAssetsAtPath(path))
                            if (asset != null && !(asset is GameObject) && !(asset is Component))
                                CheckSerialized(asset, null, path + (asset.name.Length > 0 ? " > " + asset.name : string.Empty), false, asset, items);
                    }

                    if (i % 200 == 199)
                        EditorUtility.UnloadUnusedAssetsImmediate();
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
            return items;
        }

        private static string Path(Transform t)
        {
            var parts = new List<string>();
            for (; t != null; t = t.parent)
                parts.Insert(0, t.name);
            return string.Join("/", parts.ToArray());
        }

        private static void CheckObject(GameObject go, string where, bool inScene, UnityEngine.Object asset, List<Item> items)
        {
            int scripts = GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(go);
            if (scripts > 0)
                items.Add(new Item { GameObject = go, Asset = asset, Where = where, What = scripts + " missing script(s)", Script = true, InScene = inScene });

            if (inScene && PrefabUtility.IsPrefabAssetMissing(go))
                items.Add(new Item { GameObject = go, Where = where, What = "its prefab asset is gone", InScene = true });

            foreach (var component in go.GetComponents<Component>())
                if (component != null)
                    CheckSerialized(component, go, where, inScene, asset, items);
        }

        private static void CheckSerialized(UnityEngine.Object owner, GameObject go, string where, bool inScene, UnityEngine.Object asset, List<Item> items)
        {
            var property = new SerializedObject(owner).GetIterator();
            int guard = 0;
            while (property.Next(true) && guard++ < 50000)
            {
                if (property.propertyType != SerializedPropertyType.ObjectReference || Ignored.Contains(property.name))
                    continue;
                // Missing: it remembers what it pointed at, but that thing is gone. (A plain empty field has no ID.)
                if (property.objectReferenceValue == null && property.objectReferenceInstanceIDValue != 0)
                {
                    items.Add(new Item
                    {
                        Owner = owner,
                        GameObject = go,
                        Asset = asset,
                        Where = where,
                        What = owner.GetType().Name + " > " + property.displayName,
                        Property = property.propertyPath,
                        InScene = inScene
                    });
                }
            }
        }

        /// <summary>Clears broken references in the scene (to None) and removes missing scripts, with Undo.</summary>
        internal static string ClearInScene(List<Item> items)
        {
            Undo.SetCurrentGroupName("Clear missing references");
            int group = Undo.GetCurrentGroup();
            int references = 0, scripts = 0;

            foreach (var item in items.Where(i => i.InScene))
            {
                if (item.Script && item.GameObject != null)
                {
                    Undo.RegisterCompleteObjectUndo(item.GameObject, "Remove missing scripts");
                    scripts += GameObjectUtility.RemoveMonoBehavioursWithMissingScript(item.GameObject);
                }
                else if (item.Owner != null && item.Property != null)
                {
                    var serialized = new SerializedObject(item.Owner);
                    var property = serialized.FindProperty(item.Property);
                    if (property == null || property.objectReferenceValue != null)
                        continue;
                    Undo.RecordObject(item.Owner, "Clear missing reference");
                    property.objectReferenceValue = null;
                    serialized.ApplyModifiedProperties();
                    references++;
                }
            }

            Undo.CollapseUndoOperations(group);
            return "Cleared " + references + " missing reference(s) and removed " + scripts + " missing script(s).";
        }
    }

    internal static class WPFMAMissingReferencesSection
    {
        private const string PrefKey = "WPFMA.Tools.MissingReferencesExpanded";
        private static List<WPFMAMissingReferences.Item> items;
        private static string scanned;
        private static string status;
        private static Vector2 scroll;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Missing references", items == null ? "not checked yet" : items.Count + " found", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Find everything that shows \"Missing\".",
                    "Every reference that points at something deleted, every missing script and every prefab whose asset is gone - " +
                    "in the open scenes, or in the project's prefabs, materials and other assets."),
                WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            using (new EditorGUILayout.HorizontalScope())
            {
                if (GUILayout.Button("Check the scene", GUILayout.Height(22f)))
                {
                    items = WPFMAMissingReferences.ScanScenes();
                    scanned = "the open scene(s)";
                    status = null;
                }
                if (GUILayout.Button(new GUIContent("Check the whole project", "Prefabs, materials, controllers and other assets. Can take a while."), GUILayout.Height(22f)))
                {
                    var found = WPFMAMissingReferences.ScanProject();
                    if (found != null)
                    {
                        items = found;
                        scanned = "the project";
                        status = null;
                    }
                    GUIUtility.ExitGUI();
                }
            }

            if (items == null)
                return;

            items.RemoveAll(i => i.InScene && i.GameObject == null);
            if (items.Count == 0)
            {
                EditorGUILayout.LabelField("Nothing missing in " + scanned + ".", WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
                return;
            }

            EditorGUILayout.LabelField(items.Count + " in " + scanned + ":", WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
            scroll = EditorGUILayout.BeginScrollView(scroll, GUILayout.MaxHeight(260f));
            foreach (var item in items.Take(300))
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.LabelField(new GUIContent(item.What, item.Where), WPFMAToolSection.Hint(WPFMAToolSection.MetaText), GUILayout.MinWidth(120f));
                    EditorGUILayout.LabelField(new GUIContent(Short(item.Where), item.Where), WPFMAToolSection.Hint(WPFMAToolSection.FaintText), GUILayout.MinWidth(120f));
                    if (GUILayout.Button("Show", EditorStyles.miniButton, GUILayout.Width(44f)))
                    {
                        var target = item.InScene ? (UnityEngine.Object)item.GameObject : item.Asset;
                        if (target != null)
                        {
                            Selection.activeObject = target;
                            EditorGUIUtility.PingObject(target);
                        }
                    }
                }
            }
            if (items.Count > 300)
                EditorGUILayout.LabelField("and " + (items.Count - 300) + " more.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            EditorGUILayout.EndScrollView();

            int inScene = items.Count(i => i.InScene);
            if (inScene > 0)
            {
                if (GUILayout.Button(new GUIContent("Clear " + inScene + " in the scene",
                        "Broken references become None, and missing scripts are removed. Undo puts them back."), GUILayout.Height(24f)))
                {
                    var list = items.ToList();
                    EditorApplication.delayCall += () =>
                    {
                        if (!EditorUtility.DisplayDialog("Clear " + inScene + " missing item(s)?",
                                "Broken references become None and missing scripts are removed. Undo puts them back.", "Clear", "Cancel"))
                            return;
                        status = WPFMAChangeLog.Run("Missing references", "Clear missing references", null, true, () => WPFMAMissingReferences.ClearInScene(list));
                        items = WPFMAMissingReferences.ScanScenes();
                        scanned = "the open scene(s)";
                    };
                }
            }

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

        private static string Short(string where)
        {
            int slash = where.LastIndexOf('/');
            int arrow = where.LastIndexOf(" > ", StringComparison.Ordinal);
            int cut = Math.Max(slash, arrow >= 0 ? arrow + 2 : -1);
            return cut > 0 && cut < where.Length - 1 ? where.Substring(cut + 1).Trim() : where;
        }
    }
}
#endif
