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

namespace WPFMA
{
    internal static class WPFMALightmapUvSection
    {
        private const string PrefKey = "WPFMA.Tools.LightmapUvExpanded";

        private sealed class Found
        {
            public ModelImporter Importer;
            public int Objects;
        }

        private static List<Found> fixable;
        private static List<GameObject> unfixable;
        private static string status;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Lightmap UV fixer",
                fixable == null ? "not scanned yet" : fixable.Count + " model(s) to fix", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Fix blotchy baked lighting.", "Blotchy, black or stretched baked lighting usually means a mesh has no lightmap UVs. This finds every " + "static mesh without them and turns on Unity's 'Generate Lightmap UVs' for its model."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            if (GUILayout.Button(fixable == null ? "Scan" : "Scan again"))
                EditorApplication.delayCall += Scan;

            if (fixable == null)
                return;

            if (fixable.Count == 0 && unfixable.Count == 0)
            {
                EditorGUILayout.LabelField("Every static mesh has lightmap UVs.", WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
            }

            foreach (var found in fixable.Take(15))
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.ObjectField(AssetDatabase.LoadMainAssetAtPath(found.Importer.assetPath), typeof(UnityEngine.Object), false);
                    EditorGUILayout.LabelField("used by " + found.Objects + " object(s)", WPFMAToolSection.Hint(WPFMAToolSection.FaintText), GUILayout.Width(130f));
                }
            }
            if (fixable.Count > 15)
                EditorGUILayout.LabelField("and " + (fixable.Count - 15) + " more", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            using (new EditorGUI.DisabledScope(fixable.Count == 0))
            {
                if (GUILayout.Button("Generate lightmap UVs for " + fixable.Count + " model(s)", GUILayout.Height(24f)))
                {
                    var list = fixable;
                    EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Lightmap UV fixer", "Generate lightmap UVs for " + list.Count + " model(s)", WPFMAChangeLog.MetaPaths(list.Select(f => f.Importer.assetPath)).ToList(), false, () => Fix(list));
                }
            }

            if (unfixable.Count > 0)
            {
                EditorGUILayout.LabelField(
                    unfixable.Count + " static mesh(es) are not from a model file (ProBuilder or generated meshes), so they cannot be fixed here.",
                    WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
                if (GUILayout.Button("Select them", EditorStyles.miniButton, GUILayout.Width(100f)))
                    Selection.objects = unfixable.Where(g => g != null).Cast<UnityEngine.Object>().ToArray();
            }

            EditorGUILayout.LabelField("Bake the lighting again afterwards.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

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

        private static void Scan()
        {
            var byImporter = new Dictionary<string, Found>();
            unfixable = new List<GameObject>();

            foreach (var renderer in UnityEngine.Object.FindObjectsOfType<MeshRenderer>())
            {
                var go = renderer.gameObject;
                if (!go.scene.IsValid() || !GameObjectUtility.GetStaticEditorFlags(go).HasFlag(StaticEditorFlags.ContributeGI))
                    continue;

                var filter = go.GetComponent<MeshFilter>();
                var mesh = filter != null ? filter.sharedMesh : null;
                if (mesh == null || mesh.HasVertexAttribute(VertexAttribute.TexCoord1))
                    continue;

                string path = AssetDatabase.GetAssetPath(mesh);
                var importer = AssetImporter.GetAtPath(path) as ModelImporter;
                if (importer == null || !path.StartsWith("Assets/"))
                {
                    unfixable.Add(go);
                    continue;
                }

                if (importer.generateSecondaryUV)
                    continue;

                Found found;
                if (!byImporter.TryGetValue(path, out found))
                {
                    found = new Found { Importer = importer };
                    byImporter.Add(path, found);
                }
                found.Objects++;
            }

            fixable = byImporter.Values.OrderByDescending(f => f.Objects).ToList();
            status = null;
        }

        private static string Fix(List<Found> list)
        {
            try
            {
                AssetDatabase.StartAssetEditing();
                foreach (var found in list)
                {
                    found.Importer.generateSecondaryUV = true;
                    found.Importer.SaveAndReimport();
                }
            }
            finally
            {
                AssetDatabase.StopAssetEditing();
            }

            fixable = null;
            return "Turned on lightmap UVs for " + list.Count + " model(s). Bake the lighting again to see the difference.";
        }
    }

    internal static class WPFMAEnvironmentSection
    {
        private const string PrefKey = "WPFMA.Tools.EnvironmentExpanded";

        private sealed class Preset
        {
            public string Name;
            public Color SkyTint;
            public Color Ground;
            public float Exposure;
            public float Atmosphere;
            public Vector3 SunAngle;
            public Color SunColor;
            public float SunIntensity;
            public Color Ambient;
            public bool Fog;
            public Color FogColor;
            public float FogDensity;
        }

        private static readonly Preset[] Presets =
        {
            new Preset { Name = "Day", SkyTint = new Color(0.5f, 0.5f, 0.5f), Ground = new Color(0.37f, 0.35f, 0.34f), Exposure = 1.3f, Atmosphere = 1f,
                SunAngle = new Vector3(50f, -30f, 0f), SunColor = new Color(1f, 0.96f, 0.88f), SunIntensity = 1.2f, Ambient = new Color(0.55f, 0.6f, 0.68f),
                Fog = false },
            new Preset { Name = "Sunset", SkyTint = new Color(0.62f, 0.45f, 0.4f), Ground = new Color(0.3f, 0.22f, 0.2f), Exposure = 1.1f, Atmosphere = 1.6f,
                SunAngle = new Vector3(6f, -60f, 0f), SunColor = new Color(1f, 0.6f, 0.35f), SunIntensity = 1f, Ambient = new Color(0.55f, 0.42f, 0.4f),
                Fog = true, FogColor = new Color(0.75f, 0.55f, 0.45f), FogDensity = 0.004f },
            new Preset { Name = "Night", SkyTint = new Color(0.15f, 0.18f, 0.3f), Ground = new Color(0.04f, 0.04f, 0.06f), Exposure = 0.25f, Atmosphere = 0.6f,
                SunAngle = new Vector3(40f, 120f, 0f), SunColor = new Color(0.55f, 0.65f, 1f), SunIntensity = 0.25f, Ambient = new Color(0.12f, 0.14f, 0.22f),
                Fog = true, FogColor = new Color(0.04f, 0.05f, 0.09f), FogDensity = 0.01f },
            new Preset { Name = "Overcast", SkyTint = new Color(0.45f, 0.47f, 0.5f), Ground = new Color(0.3f, 0.3f, 0.3f), Exposure = 0.9f, Atmosphere = 2.5f,
                SunAngle = new Vector3(65f, -20f, 0f), SunColor = new Color(0.85f, 0.88f, 0.92f), SunIntensity = 0.55f, Ambient = new Color(0.55f, 0.57f, 0.6f),
                Fog = true, FogColor = new Color(0.62f, 0.64f, 0.67f), FogDensity = 0.008f },
            new Preset { Name = "Cosy indoors", SkyTint = new Color(0.3f, 0.25f, 0.22f), Ground = new Color(0.15f, 0.12f, 0.1f), Exposure = 0.5f, Atmosphere = 1f,
                SunAngle = new Vector3(35f, -45f, 0f), SunColor = new Color(1f, 0.78f, 0.55f), SunIntensity = 0.6f, Ambient = new Color(0.32f, 0.25f, 0.2f),
                Fog = false }
        };

        private static string status;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Environment presets", "sky, sun, ambient, fog", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Sky, sun, ambient and fog.", "Sets the sky, sun, ambient light and fog in one click. A starting point - tweak it in Window > Rendering > Lighting."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            using (new EditorGUILayout.HorizontalScope())
            {
                foreach (var preset in Presets)
                {
                    if (GUILayout.Button(preset.Name, GUILayout.Height(24f)))
                    {
                        var chosen = preset;
                        EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Environment presets", "Apply '" + chosen.Name + "'", new[] { WPFMAWorldTypes.SceneFolder() + "/Sky - " + chosen.Name + ".mat" }, true, () => Apply(chosen));
                    }
                }
            }

            EditorGUILayout.LabelField(new GUIContent("Procedural sky and the main light.", "Uses Unity's procedural sky and the scene's main directional light (one is added if there is none). Bake the lighting again afterwards."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

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

        private static string Apply(Preset preset)
        {
            var shader = Shader.Find("Skybox/Procedural");
            if (shader == null)
                return "Unity's procedural sky shader is missing.";

            string folder = WPFMAWorldTypes.SceneFolder();
            WPFMAAvatarFolders.Ensure(folder);
            string path = folder + "/Sky - " + preset.Name + ".mat";

            var sky = AssetDatabase.LoadAssetAtPath<Material>(path);
            if (sky == null)
            {
                sky = new Material(shader);
                AssetDatabase.CreateAsset(sky, path);
            }

            sky.shader = shader;
            sky.SetColor("_SkyTint", preset.SkyTint);
            sky.SetColor("_GroundColor", preset.Ground);
            sky.SetFloat("_Exposure", preset.Exposure);
            sky.SetFloat("_AtmosphereThickness", preset.Atmosphere);
            sky.SetFloat("_SunSize", 0.04f);
            EditorUtility.SetDirty(sky);
            AssetDatabase.SaveAssets();

            var sun = RenderSettings.sun;
            if (sun == null)
                sun = UnityEngine.Object.FindObjectsOfType<Light>().FirstOrDefault(l => l.type == LightType.Directional);
            if (sun == null)
            {
                var go = new GameObject("Sun");
                Undo.RegisterCreatedObjectUndo(go, "Environment preset");
                sun = go.AddComponent<Light>();
                sun.type = LightType.Directional;
                sun.lightmapBakeType = LightmapBakeType.Mixed;
            }

            Undo.RecordObjects(new UnityEngine.Object[] { sun, sun.transform }, "Environment preset");
            sun.transform.rotation = Quaternion.Euler(preset.SunAngle);
            sun.color = preset.SunColor;
            sun.intensity = preset.SunIntensity;

            RenderSettings.skybox = sky;
            RenderSettings.sun = sun;
            RenderSettings.ambientMode = AmbientMode.Flat;
            RenderSettings.ambientLight = preset.Ambient;
            RenderSettings.fog = preset.Fog;
            if (preset.Fog)
            {
                RenderSettings.fogMode = FogMode.ExponentialSquared;
                RenderSettings.fogColor = preset.FogColor;
                RenderSettings.fogDensity = preset.FogDensity;
            }

            DynamicGI.UpdateEnvironment();
            EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
            return "Applied '" + preset.Name + "'. Bake the lighting again so baked light matches.";
        }
    }

    internal static class WPFMADrawDistanceSection
    {
        private const string PrefKey = "WPFMA.Tools.DrawDistanceExpanded";

        private static float maxSize { get { return WPFMAToolDefaults.WorldCullBelowSize; } set { WPFMAToolDefaults.WorldCullBelowSize = value; } }
        private static float cullPercent { get { return WPFMAToolDefaults.WorldCullPercent; } set { WPFMAToolDefaults.WorldCullPercent = value; } }
        private static bool selectionOnly;
        private static string status;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Draw-distance culling", "hide small props far away", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Cull tiny far-away props.", "Small props stop drawing when they are tiny on screen - nobody notices a cup 40 m away, but the GPU does. " + "This adds an LOD Group that culls them."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            maxSize = EditorGUILayout.Slider("Props smaller than (m)", maxSize, 0.1f, 5f);
            cullPercent = EditorGUILayout.Slider("Hide below (% of screen)", cullPercent, 0.2f, 10f);
            selectionOnly = EditorGUILayout.ToggleLeft("Only the selected objects", selectionOnly);

            if (GUILayout.Button("Add culling", GUILayout.Height(24f)))
            {
                float size = maxSize, percent = cullPercent;
                bool selection = selectionOnly;
                EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Draw-distance culling", "Add culling to small props", null, true, () => Apply(size, percent, selection));
            }

            if (GUILayout.Button("Remove this kind of culling", EditorStyles.miniButton, GUILayout.Width(180f)))
                EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Draw-distance culling", "Remove culling", null, true, () => Remove());

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

        private static string Apply(float size, float percent, bool selection)
        {
            IEnumerable<Renderer> renderers = selection
                ? Selection.gameObjects.Where(g => !EditorUtility.IsPersistent(g)).SelectMany(g => g.GetComponentsInChildren<Renderer>())
                : UnityEngine.Object.FindObjectsOfType<Renderer>();

            int added = 0;
            Undo.SetCurrentGroupName("Draw-distance culling");
            int group = Undo.GetCurrentGroup();

            foreach (var renderer in renderers.Distinct())
            {
                if (renderer is ParticleSystemRenderer || !renderer.gameObject.scene.IsValid())
                    continue;
                if (renderer.GetComponentInParent<LODGroup>() != null)
                    continue;

                var extents = renderer.bounds.size;
                if (Mathf.Max(extents.x, Mathf.Max(extents.y, extents.z)) > size)
                    continue;

                var lod = Undo.AddComponent<LODGroup>(renderer.gameObject);
                lod.SetLODs(new[] { new LOD(percent / 100f, new[] { renderer }) { fadeTransitionWidth = 0f } });
                lod.RecalculateBounds();
                var serialized = new SerializedObject(lod);
                var fade = serialized.FindProperty("m_FadeMode");
                if (fade != null)
                    fade.intValue = 0;
                serialized.ApplyModifiedPropertiesWithoutUndo();
                added++;
            }

            Undo.CollapseUndoOperations(group);
            return added == 0 ? "No props small enough." : "Added culling to " + added + " prop(s). Ctrl+Z removes it.";
        }

        private static string Remove()
        {
            int removed = 0;
            foreach (var lod in UnityEngine.Object.FindObjectsOfType<LODGroup>())
            {
                var lods = lod.GetLODs();
                if (lods.Length != 1 || lods[0].renderers == null || lods[0].renderers.Length != 1 ||
                    lods[0].renderers[0] == null || lods[0].renderers[0].gameObject != lod.gameObject)
                    continue;

                Undo.DestroyObjectImmediate(lod);
                removed++;
            }

            return removed == 0 ? "No single-level culling groups found." : "Removed culling from " + removed + " prop(s).";
        }
    }
}
#endif
