// 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 System.Reflection;
using UnityEditor;
using UnityEngine;
using Issue = WPFMA.WPFMAPreUploadCheck.Issue;
using Severity = WPFMA.WPFMAPreUploadCheck.Severity;

namespace WPFMA
{
    internal static class WPFMAWorldCheck
    {
        internal const int SetupPage = 0;
        internal const int CheckPage = 2;
        internal const int LightingPage = 3;
        internal const int OptimizePage = 4;

        private static readonly string[] BadEffects = { "ChromaticAberration", "ScreenSpaceReflections", "AmbientOcclusion" };

        internal static List<Issue> Run()
        {
            var issues = new List<Issue>();

            Guard(issues, "Scene Descriptor", () => Descriptor(issues));
            Guard(issues, "Layers", () => Layers(issues));
            Guard(issues, "Missing scripts", () => MissingScripts(issues));
            Guard(issues, "Materials", () => Materials(issues));
            Guard(issues, "Colliders", () => Colliders(issues));
            Guard(issues, "Lights", () => Lights(issues));
            Guard(issues, "Mirrors and video", () => MirrorsAndVideo(issues));
            Guard(issues, "Baking", () => Baking(issues));
            Guard(issues, "Light volumes", () => LightVolumes(issues));
            Guard(issues, "Post-processing", () => PostProcessing(issues));
            Guard(issues, "Textures", () => Textures(issues));
            Guard(issues, "Quest", () => Quest(issues));

            return issues.OrderBy(i => i.Severity).ToList();
        }

        private static void Guard(List<Issue> issues, string name, Action check)
        {
            try
            {
                check();
            }
            catch (Exception e)
            {
                issues.Add(new Issue { Severity = Severity.Info, Title = name + " could not be checked", Detail = e.Message });
            }
        }

        private static Issue Pass(string title)
        {
            return new Issue { Severity = Severity.Pass, Title = title };
        }

        private static void Descriptor(List<Issue> issues)
        {
            if (!WPFMAWorldTypes.WorldSdkInstalled)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Error,
                    Title = "The VRChat world SDK is not installed",
                    Detail = "Worlds need the world SDK to upload. Install it from the Importer tab or the Creator Companion."
                });
                return;
            }

            var descriptors = WPFMAWorldTypes.Objects(WPFMAWorldTypes.SceneDescriptorBase);
            if (descriptors.Count == 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Error,
                    Title = "No Scene Descriptor",
                    Detail = "VRChat needs exactly one VRCWorld object in the scene to upload it.",
                    FixLabel = "Add VRCWorld",
                    Fix = () => WPFMAWorldSetup.AddDescriptor()
                });
                return;
            }

            if (descriptors.Count > 1)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Error,
                    Title = descriptors.Count + " Scene Descriptors",
                    Detail = "There must be exactly one. Delete the extras.",
                    Show = descriptors.Select(d => (UnityEngine.Object)d.gameObject).ToArray()
                });
            }

            var descriptor = descriptors[0];
            var serialized = new SerializedObject(descriptor);
            var spawns = serialized.FindProperty("spawns");
            var spawnTransforms = new List<Transform>();
            if (spawns != null)
                for (int i = 0; i < spawns.arraySize; i++)
                    if (spawns.GetArrayElementAtIndex(i).objectReferenceValue is Transform t)
                        spawnTransforms.Add(t);

            if (spawnTransforms.Count == 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = "No spawn points",
                    Detail = "Players appear at the Scene Descriptor's position.",
                    FixLabel = "Add one at the Scene view",
                    Fix = () => WPFMAWorldSetup.AddSpawn()
                });
            }
            else
            {
                issues.Add(Pass(spawnTransforms.Count + " spawn point(s)"));
            }

            var respawn = serialized.FindProperty("RespawnHeightY");
            if (respawn != null)
            {
                float height = respawn.floatValue;
                var below = spawnTransforms.Where(s => s.position.y <= height).ToList();
                if (below.Count > 0 || (spawnTransforms.Count == 0 && descriptor.transform.position.y <= height))
                {
                    issues.Add(new Issue
                    {
                        Severity = Severity.Error,
                        Title = "Players spawn below the respawn height",
                        Detail = "They would respawn forever. The respawn height is " + height.ToString("0.#") + ".",
                        FixLabel = "Put it under the map",
                        Fix = () => WPFMAWorldSetup.SetRespawnHeight()
                    });
                }
                else if (height >= WPFMAWorldTypes.SceneBounds().min.y)
                {
                    issues.Add(new Issue
                    {
                        Severity = Severity.Warning,
                        Title = "Respawn height cuts through the map",
                        Detail = "Anyone who walks below " + height.ToString("0.#") + " gets respawned.",
                        FixLabel = "Put it under the map",
                        Fix = () => WPFMAWorldSetup.SetRespawnHeight()
                    });
                }
                else
                {
                    issues.Add(Pass("Respawn height is under the map"));
                }
            }

            foreach (var spawn in spawnTransforms)
            {
                if (!Physics.Raycast(spawn.position + Vector3.up * 0.5f, Vector3.down, 20f))
                {
                    issues.Add(new Issue
                    {
                        Severity = Severity.Warning,
                        Title = "'" + spawn.name + "' has nothing to stand on",
                        Detail = "No collider within 20 m below it, so players spawn and fall.",
                        Show = new UnityEngine.Object[] { spawn.gameObject }
                    });
                }
            }

            var reference = serialized.FindProperty("ReferenceCamera");
            if (reference != null && reference.objectReferenceValue == null)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Info,
                    Title = "No reference camera",
                    Detail = "Without one VRChat uses default camera settings, and post-processing cannot work.",
                    FixLabel = "Add one",
                    Fix = () => WPFMAWorldSetup.AddReferenceCamera(false)
                });
            }
        }

        private static void Layers(List<Issue> issues)
        {
            var missing = new[] { "Player", "PlayerLocal", "MirrorReflection" }.Where(n => LayerMask.NameToLayer(n) < 0).ToList();
            if (missing.Count == 0)
            {
                issues.Add(Pass("VRChat's layers are set up"));
                return;
            }

            issues.Add(new Issue
            {
                Severity = Severity.Error,
                Title = "VRChat's layers are not set up",
                Detail = "Missing: " + string.Join(", ", missing.ToArray()) + ". Open VRChat SDK > Show Control Panel > Builder and press " +
                         "'Setup Layers for VRChat' and 'Set Collision Matrix'."
            });
        }

        private static void MissingScripts(List<Issue> issues)
        {
            var broken = WPFMAWorldTypes.SceneObjects()
                .Where(g => GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(g) > 0)
                .ToArray();

            if (broken.Length == 0)
            {
                issues.Add(Pass("No missing scripts"));
                return;
            }

            issues.Add(new Issue
            {
                Severity = Severity.Error,
                Title = "Missing scripts on " + broken.Length + " object(s)",
                Detail = "Components whose script is gone. VRChat's builder refuses these.",
                Show = broken.Cast<UnityEngine.Object>().ToArray(),
                FixLabel = "Remove them",
                Fix = () =>
                {
                    foreach (var go in broken)
                    {
                        if (go == null)
                            continue;
                        Undo.RegisterCompleteObjectUndo(go, "Remove missing scripts");
                        GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go);
                    }
                }
            });
        }

        private static void Materials(List<Issue> issues)
        {
            var pink = new HashSet<GameObject>();
            var shaders = new HashSet<string>();

            foreach (var renderer in UnityEngine.Object.FindObjectsOfType<Renderer>(true))
            {
                if (!renderer.gameObject.scene.IsValid())
                    continue;

                foreach (var material in renderer.sharedMaterials)
                {
                    if (material == null)
                        continue;
                    var shader = material.shader;
                    if (shader == null || shader.name == "Hidden/InternalErrorShader" || !shader.isSupported)
                    {
                        pink.Add(renderer.gameObject);
                        shaders.Add(shader != null ? shader.name : "(none)");
                    }
                }
            }

            if (pink.Count == 0)
            {
                issues.Add(Pass("Every material has a working shader"));
                return;
            }

            issues.Add(new Issue
            {
                Severity = Severity.Error,
                Title = pink.Count + " object(s) will show pink",
                Detail = "Missing or broken shaders: " + string.Join(", ", shaders.Take(4).ToArray()) + ".",
                Show = pink.Cast<UnityEngine.Object>().ToArray(),
                ToolPage = OptimizePage,
                ToolKey = "WPFMA.Tools.ShaderSwapExpanded"
            });
        }

        private static void Colliders(List<Issue> issues)
        {
            int colliders = UnityEngine.Object.FindObjectsOfType<Collider>().Count(c => c.enabled && !c.isTrigger);
            if (colliders == 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Error,
                    Title = "Nothing to stand on",
                    Detail = "The scene has no solid colliders, so players fall through everything."
                });
                return;
            }

            issues.Add(Pass(colliders + " solid collider(s)"));
        }

        private static void Lights(List<Issue> issues)
        {
            var lights = UnityEngine.Object.FindObjectsOfType<Light>()
                .Where(l => l.enabled && l.gameObject.activeInHierarchy && l.gameObject.scene.IsValid())
                .ToList();

            var realtime = lights.Where(l => l.lightmapBakeType == LightmapBakeType.Realtime).ToList();
            var shadowed = realtime.Where(l => l.shadows != LightShadows.None).ToList();

            if (realtime.Count > 1 || shadowed.Count > 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = realtime.Count + " realtime light(s)" + (shadowed.Count > 0 ? ", " + shadowed.Count + " casting shadows" : string.Empty),
                    Detail = "Realtime lights are expensive in VRChat - a point light's shadows cost about as much as a mirror. Bake them instead.",
                    Show = realtime.Select(l => (UnityEngine.Object)l.gameObject).ToArray(),
                    FixLabel = "Make them baked",
                    Fix = () =>
                    {
                        Undo.RecordObjects(realtime.Cast<UnityEngine.Object>().ToArray(), "Bake lights");
                        foreach (var light in realtime)
                        {
                            light.lightmapBakeType = LightmapBakeType.Baked;
                            EditorUtility.SetDirty(light);
                        }
                    }
                });
            }
            else
            {
                issues.Add(Pass(realtime.Count == 0 ? "No realtime lights" : "One realtime light, no realtime shadows"));
            }
        }

        private static void MirrorsAndVideo(List<Issue> issues)
        {
            var mirrors = WPFMAWorldTypes.Objects(WPFMAWorldTypes.Mirror);
            var on = mirrors.Where(m => m.gameObject.activeInHierarchy && ((Behaviour)m).enabled).ToList();

            if (mirrors.Count > 1)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = mirrors.Count + " mirrors",
                    Detail = "Mirrors are the most expensive thing in a world. VRChat recommends one.",
                    Show = mirrors.Select(m => (UnityEngine.Object)m.gameObject).ToArray()
                });
            }

            if (on.Count > 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = on.Count + " mirror(s) on by default",
                    Detail = "VRChat recommends mirrors start off, with a toggle to turn them on.",
                    Show = on.Select(m => (UnityEngine.Object)m.gameObject).ToArray(),
                    FixLabel = "Switch them off",
                    Fix = () =>
                    {
                        foreach (var mirror in on)
                        {
                            if (mirror == null)
                                continue;
                            Undo.RecordObject(mirror.gameObject, "Switch mirror off");
                            mirror.gameObject.SetActive(false);
                        }
                    }
                });
            }

            int videos = WPFMAWorldTypes.Objects(WPFMAWorldTypes.UnityVideo).Count + WPFMAWorldTypes.Objects(WPFMAWorldTypes.AVProVideo).Count;
            if (videos > 2)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = videos + " video players",
                    Detail = "VRChat recommends at most two per room."
                });
            }

            if (mirrors.Count <= 1 && on.Count == 0 && videos <= 2)
                issues.Add(Pass("Mirrors and video players are within VRChat's advice"));
        }

        private static void Baking(List<Issue> issues)
        {
            var staticGi = UnityEngine.Object.FindObjectsOfType<MeshRenderer>()
                .Count(r => GameObjectUtility.GetStaticEditorFlags(r.gameObject).HasFlag(StaticEditorFlags.ContributeGI));

            if (staticGi == 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = "Nothing is marked static",
                    Detail = "Static objects are what get baked lighting and occlusion culling. The Lighting helper can mark them.",
                    ToolPage = LightingPage,
                    ToolKey = "WPFMA.Tools.LightingExpanded"
                });
            }
            else if (Lightmapping.lightingDataAsset == null)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = "Lighting has not been baked",
                    Detail = staticGi + " static object(s) are waiting for baked light.",
                    ToolPage = LightingPage,
                    ToolKey = "WPFMA.Tools.LightingExpanded"
                });
            }
            else
            {
                issues.Add(Pass("Lighting is baked (" + LightmapSettings.lightmaps.Length + " lightmap(s))"));
            }

            int renderers = UnityEngine.Object.FindObjectsOfType<MeshRenderer>().Length;
            if (renderers > 50 && StaticOcclusionCulling.umbraDataSize == 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = "Occlusion culling is not baked",
                    Detail = "Without it everything renders even when it is behind walls. VRChat calls this exceedingly important.",
                    ToolPage = OptimizePage,
                    ToolKey = "WPFMA.Tools.OcclusionExpanded"
                });
            }
            else if (StaticOcclusionCulling.umbraDataSize > 0)
            {
                issues.Add(Pass("Occlusion culling is baked"));
            }
        }

        private static void LightVolumes(List<Issue> issues)
        {
            if (!WPFMALightVolumes.Installed)
                return;

            var volumes = WPFMALightVolumes.Volumes();
            if (volumes.Count == 0)
                return;

            var unbaked = volumes.Where(v => !WPFMALightVolumes.IsBaked(v)).ToList();
            var duplicates = WPFMALightVolumes.DuplicateNames();

            if (volumes.Count > WPFMALightVolumes.MaxVolumes)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = volumes.Count + " light volumes",
                    Detail = "VRC Light Volumes shows at most " + WPFMALightVolumes.MaxVolumes + " at once.",
                    ToolPage = LightingPage,
                    ToolKey = "WPFMA.Tools.LightVolumesExpanded"
                });
            }

            if (duplicates.Count > 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = "Light volumes share names",
                    Detail = string.Join(", ", duplicates.ToArray()) + ". Each needs its own name or their baked textures clash.",
                    FixLabel = "Give each its own name",
                    Fix = () => WPFMALightVolumes.FixNames()
                });
            }

            if (unbaked.Count > 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = unbaked.Count + " light volume(s) not baked",
                    Detail = "They light nothing until the scene's lighting is baked again.",
                    Show = unbaked.Select(v => (UnityEngine.Object)v.gameObject).ToArray(),
                    ToolPage = LightingPage,
                    ToolKey = "WPFMA.Tools.LightingExpanded"
                });
            }

            if (unbaked.Count == 0 && duplicates.Count == 0 && volumes.Count <= WPFMALightVolumes.MaxVolumes)
                issues.Add(Pass(volumes.Count + " light volume(s), all baked"));
        }

        private static void PostProcessing(List<Issue> issues)
        {
            var volumeType = WPFMAWorldTypes.Find("UnityEngine.Rendering.PostProcessing.PostProcessVolume");
            if (volumeType == null)
                return;

            var flagged = new List<KeyValuePair<UnityEngine.Object, object>>();
            var names = new HashSet<string>();

            foreach (var volume in UnityEngine.Object.FindObjectsOfType(volumeType, true).OfType<Component>())
            {
                var profileField = volumeType.GetField("sharedProfile");
                var profile = profileField != null ? profileField.GetValue(volume) as ScriptableObject : null;
                if (profile == null)
                    continue;

                var settingsField = profile.GetType().GetField("settings");
                var list = settingsField != null ? settingsField.GetValue(profile) as System.Collections.IEnumerable : null;
                if (list == null)
                    continue;

                foreach (var effect in list)
                {
                    if (effect == null || !BadEffects.Contains(effect.GetType().Name) || !IsOn(effect))
                        continue;
                    flagged.Add(new KeyValuePair<UnityEngine.Object, object>(profile, effect));
                    names.Add(effect.GetType().Name);
                }
            }

            if (flagged.Count == 0)
                return;

            issues.Add(new Issue
            {
                Severity = Severity.Warning,
                Title = "Post-processing effects VRChat warns against",
                Detail = string.Join(", ", names.ToArray()) + " look wrong or cost a lot in VR.",
                FixLabel = "Turn them off",
                Fix = () =>
                {
                    foreach (var pair in flagged)
                    {
                        var active = pair.Value.GetType().GetField("active", BindingFlags.Public | BindingFlags.Instance);
                        if (active != null)
                        {
                            Undo.RecordObject((UnityEngine.Object)pair.Value, "Disable effect");
                            active.SetValue(pair.Value, false);
                            EditorUtility.SetDirty((UnityEngine.Object)pair.Value);
                            EditorUtility.SetDirty(pair.Key);
                        }
                    }
                    AssetDatabase.SaveAssets();
                }
            });
        }

        private static bool IsOn(object effect)
        {
            var active = effect.GetType().GetField("active", BindingFlags.Public | BindingFlags.Instance);
            if (active != null && !(bool)active.GetValue(effect))
                return false;

            var enabled = effect.GetType().GetField("enabled", BindingFlags.Public | BindingFlags.Instance);
            var parameter = enabled != null ? enabled.GetValue(effect) : null;
            var value = parameter != null ? parameter.GetType().GetField("value", BindingFlags.Public | BindingFlags.Instance) : null;
            return value == null || (bool)value.GetValue(parameter);
        }

        private static void Textures(List<Issue> issues)
        {
            var textures = WPFMATextureOptimizer.Collect(null);
            var heavy = textures.Where(t => t.Importer != null &&
                                            (t.Importer.textureCompression == TextureImporterCompression.Uncompressed || t.Importer.maxTextureSize > 2048))
                .ToList();

            if (heavy.Count == 0)
            {
                issues.Add(Pass(textures.Count + " texture(s), none uncompressed or over 2048"));
                return;
            }

            issues.Add(new Issue
            {
                Severity = Severity.Info,
                Title = heavy.Count + " texture(s) are uncompressed or over 2048",
                Detail = "Textures are usually most of a world's download size. The texture optimizer fixes them all at once.",
                ToolPage = OptimizePage,
                ToolKey = "WPFMA.Tools.TextureOptimizerExpanded"
            });
        }

        private static void Quest(List<Issue> issues)
        {
            if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android)
                return;

            var desktop = new HashSet<Material>();
            foreach (var renderer in UnityEngine.Object.FindObjectsOfType<Renderer>())
                foreach (var material in renderer.sharedMaterials)
                    if (material != null && material.shader != null && !material.shader.name.StartsWith("VRChat/Mobile/"))
                        desktop.Add(material);

            if (desktop.Count > 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = desktop.Count + " material(s) are not using VRChat's mobile shaders",
                    Detail = "You are building for Quest. Swap them with Bulk shader swap (or set them up in EasyQuestSwitch).",
                    ToolPage = OptimizePage,
                    ToolKey = "WPFMA.Tools.ShaderSwapExpanded"
                });
            }

            issues.Add(new Issue
            {
                Severity = Severity.Info,
                Title = "Quest worlds must be under 100 MB",
                Detail = "That is after VRChat compresses the build. World stats gives a rough estimate before you build."
            });
        }
    }

    internal static class WPFMAWorldCheckSection
    {
        private const string PrefKey = "WPFMA.Tools.WorldCheckExpanded";

        private static List<Issue> issues;
        private static bool showPasses;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "World pre-upload check", Detail(), PrefKey, Body);
        }

        private static string Detail()
        {
            if (issues == null)
                return "not run yet";

            int errors = issues.Count(i => i.Severity == Severity.Error);
            int warnings = issues.Count(i => i.Severity == Severity.Warning);
            return errors + warnings == 0 ? "all clear" : errors + " error(s), " + warnings + " warning(s)";
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Every check before you upload.", "Checks the open scene against VRChat's world advice: descriptor, spawns, layers, missing scripts, pink " + "materials, colliders, realtime lights, mirrors, video players, baking, post-processing and textures."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            if (GUILayout.Button(issues == null ? "Run check" : "Check again", GUILayout.Height(24f)))
                EditorApplication.delayCall += Run;

            if (issues == null)
                return;

            var problems = issues.Where(i => i.Severity != Severity.Pass).ToList();
            var passes = issues.Where(i => i.Severity == Severity.Pass).ToList();

            if (problems.Count == 0)
            {
                EditorGUILayout.Space(4f);
                EditorGUILayout.LabelField("Everything checks out - ready to upload.",
                    new GUIStyle(EditorStyles.boldLabel) { normal = { textColor = WPFMAToolSection.OkGreen } });
            }

            foreach (var issue in problems)
                WPFMAIssueView.Draw(issue, Run, WPFMAWorldTypes.Reveal);

            EditorGUILayout.Space(4f);
            showPasses = EditorGUILayout.Foldout(showPasses, passes.Count + " check(s) passed", true);
            if (showPasses)
                foreach (var pass in passes)
                    EditorGUILayout.LabelField("✓  " + pass.Title, WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
        }

        private static void Run()
        {
            WPFMAWorldTypes.Invalidate();
            try
            {
                issues = WPFMAWorldCheck.Run();
            }
            catch (Exception e)
            {
                issues = new List<Issue> { new Issue { Severity = Severity.Error, Title = "The check failed", Detail = e.Message } };
                Debug.LogWarning("[WPFMA-SDK] World check failed: " + e);
            }
        }
    }
}
#endif
