// 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 WPFMALightingHelper
    {
        internal const StaticEditorFlags WorldStatic =
            StaticEditorFlags.ContributeGI | StaticEditorFlags.OccluderStatic | StaticEditorFlags.OccludeeStatic |
            StaticEditorFlags.BatchingStatic | StaticEditorFlags.ReflectionProbeStatic;

        private static readonly string[] MovingTypes =
        {
            WPFMAWorldTypes.Pickup, WPFMAWorldTypes.Station, WPFMAWorldTypes.Udon, WPFMAWorldTypes.Mirror,
            WPFMAWorldTypes.UnityVideo, WPFMAWorldTypes.AVProVideo
        };

        internal static List<GameObject> Candidates(bool selectionOnly)
        {
            IEnumerable<GameObject> source = selectionOnly
                ? Selection.gameObjects.Where(g => !EditorUtility.IsPersistent(g)).SelectMany(g => g.GetComponentsInChildren<Transform>(true)).Select(t => t.gameObject)
                : WPFMAWorldTypes.SceneObjects();

            var moving = new HashSet<GameObject>();
            foreach (var typeName in MovingTypes)
            {
                foreach (var component in WPFMAWorldTypes.Objects(typeName))
                    foreach (var t in component.GetComponentsInChildren<Transform>(true))
                        moving.Add(t.gameObject);
            }

            return source.Distinct()
                .Where(g => g.GetComponent<MeshRenderer>() != null && g.GetComponent<MeshFilter>() != null)
                .Where(g => !moving.Contains(g))
                .Where(g => g.GetComponentInParent<Animator>() == null && g.GetComponentInParent<Rigidbody>() == null)
                .ToList();
        }

        internal static string MarkStatic(bool selectionOnly)
        {
            var targets = Candidates(selectionOnly);
            if (targets.Count == 0)
                return selectionOnly ? "Nothing in the selection can be static." : "Nothing in the scene can be static.";

            Undo.RecordObjects(targets.Cast<UnityEngine.Object>().ToArray(), "Mark static");
            foreach (var go in targets)
                GameObjectUtility.SetStaticEditorFlags(go, GameObjectUtility.GetStaticEditorFlags(go) | WorldStatic);

            return "Marked " + targets.Count + " object(s) static (lightmaps, occlusion, batching, reflection probes). " +
                   "Objects that move - pickups, seats, Udon, animated or physics objects - were left alone.";
        }

        internal static string ClearStatic()
        {
            var targets = Selection.gameObjects.Where(g => !EditorUtility.IsPersistent(g))
                .SelectMany(g => g.GetComponentsInChildren<Transform>(true)).Select(t => t.gameObject).Distinct().ToList();
            if (targets.Count == 0)
                return "Select the objects to un-static first.";

            Undo.RecordObjects(targets.Cast<UnityEngine.Object>().ToArray(), "Clear static");
            foreach (var go in targets)
                GameObjectUtility.SetStaticEditorFlags(go, 0);
            return "Cleared static on " + targets.Count + " object(s).";
        }

        internal static string SetLights(LightmapBakeType mode)
        {
            var lights = UnityEngine.Object.FindObjectsOfType<Light>().Where(l => l.gameObject.scene.IsValid() && l.lightmapBakeType == LightmapBakeType.Realtime).ToList();
            if (lights.Count == 0)
                return "There are no realtime lights.";

            Undo.RecordObjects(lights.Cast<UnityEngine.Object>().ToArray(), "Change lights");
            foreach (var light in lights)
            {
                light.lightmapBakeType = mode;
                EditorUtility.SetDirty(light);
            }
            return "Changed " + lights.Count + " realtime light(s) to " + mode + ".";
        }

        // ---- Bakery ---------------------------------------------------------------------------------------------------
        // Bakery bakes from its own components (BakeryPointLight and so on), so the Unity Light next to one is often
        // left Realtime or Mixed. In VRChat that's a real realtime light, costing performance on top of the bake.

        private static bool? bakery;

        internal static bool BakeryInstalled
        {
            get
            {
                if (bakery == null)
                    bakery = AppDomain.CurrentDomain.GetAssemblies().Any(a => a.GetType("BakeryPointLight", false) != null || a.GetType("ftRenderLightmap", false) != null);
                return bakery.Value;
            }
        }

        private static bool IsBakery(Component component)
        {
            return component != null && component.GetType().Name.StartsWith("Bakery", StringComparison.Ordinal);
        }

        /// <summary>Has a Bakery light on the same object, so Bakery bakes it.</summary>
        internal static bool BakedByBakery(Light light)
        {
            return light.GetComponents<Component>().Any(c => IsBakery(c) && (c.GetType().Name.EndsWith("Light", StringComparison.Ordinal) || c.GetType().Name == "BakeryLightMesh"));
        }

        /// <summary>Unity lights that would light the world in VRChat: in the scene, switched on, not Baked, not EditorOnly.</summary>
        internal static List<Light> LiveUnityLights()
        {
            return UnityEngine.Object.FindObjectsOfType<Light>()
                .Where(l => l.gameObject.scene.IsValid() && l.enabled && l.lightmapBakeType != LightmapBakeType.Baked && !InEditorOnly(l.transform))
                .ToList();
        }

        private static bool InEditorOnly(Transform t)
        {
            for (; t != null; t = t.parent)
                if (t.CompareTag("EditorOnly"))
                    return true;
            return false;
        }

        /// <summary>
        /// Keeps Bakery-baked Unity lights out of VRChat. A light on its own object is tagged EditorOnly (left out of
        /// the upload, still there for Bakery); one sharing an object with other things, like a lamp model, only has
        /// its Light switched off so nothing else goes missing.
        /// </summary>
        internal static string LeaveOutBakedByBakery()
        {
            var lights = LiveUnityLights().Where(BakedByBakery).ToList();
            if (lights.Count == 0)
                return "No Bakery-baked Unity lights are left on.";

            int tagged = 0;
            int switchedOff = 0;
            foreach (var light in lights)
            {
                var go = light.gameObject;
                bool alone = go.transform.childCount == 0 &&
                             go.GetComponents<Component>().All(c => c is Transform || c is Light || IsBakery(c));
                if (alone)
                {
                    Undo.RecordObject(go, "Leave Bakery lights out");
                    go.tag = "EditorOnly";
                    tagged++;
                }
                else
                {
                    Undo.RecordObject(light, "Leave Bakery lights out");
                    light.enabled = false;
                    switchedOff++;
                }
                EditorUtility.SetDirty(go);
            }

            return "Left " + lights.Count + " Bakery-baked light(s) out of VRChat: " + tagged + " tagged EditorOnly, " +
                   switchedOff + " switched off (their objects hold other things). Bakery still bakes them.";
        }

        internal static string AddLightProbes(float spacing, bool selectionOnly)
        {
            Bounds bounds;
            if (selectionOnly && Selection.gameObjects.Length > 0)
            {
                var renderers = Selection.gameObjects.SelectMany(g => g.GetComponentsInChildren<Renderer>()).ToList();
                if (renderers.Count == 0)
                    return "The selection has no renderers to size the grid from.";
                bounds = renderers[0].bounds;
                foreach (var r in renderers.Skip(1))
                    bounds.Encapsulate(r.bounds);
            }
            else
            {
                bounds = WPFMAWorldTypes.SceneBounds();
            }

            spacing = Mathf.Max(0.5f, spacing);
            int nx = Mathf.Max(2, Mathf.CeilToInt(bounds.size.x / spacing) + 1);
            int ny = Mathf.Max(2, Mathf.CeilToInt(Mathf.Min(bounds.size.y, 12f) / spacing) + 1);
            int nz = Mathf.Max(2, Mathf.CeilToInt(bounds.size.z / spacing) + 1);

            while ((long)nx * ny * nz > 6000)
            {
                spacing *= 1.25f;
                nx = Mathf.Max(2, Mathf.CeilToInt(bounds.size.x / spacing) + 1);
                ny = Mathf.Max(2, Mathf.CeilToInt(Mathf.Min(bounds.size.y, 12f) / spacing) + 1);
                nz = Mathf.Max(2, Mathf.CeilToInt(bounds.size.z / spacing) + 1);
            }

            var positions = new List<Vector3>();
            var start = new Vector3(bounds.min.x, bounds.min.y + 0.5f, bounds.min.z);
            for (int x = 0; x < nx; x++)
                for (int y = 0; y < ny; y++)
                    for (int z = 0; z < nz; z++)
                        positions.Add(start + new Vector3(x * spacing, y * spacing, z * spacing));

            var go = new GameObject("Light Probes");
            Undo.RegisterCreatedObjectUndo(go, "Add light probes");
            var group = go.AddComponent<LightProbeGroup>();
            group.probePositions = positions.ToArray();
            Selection.activeGameObject = go;

            return "Added " + positions.Count + " light probes every " + spacing.ToString("0.#") + " m. They light avatars and moving objects with your baked light.";
        }

        internal static string AddReflectionProbe()
        {
            var bounds = WPFMAWorldTypes.SceneBounds();
            var go = new GameObject("Reflection Probe");
            Undo.RegisterCreatedObjectUndo(go, "Add reflection probe");
            go.transform.position = bounds.center;
            var probe = go.AddComponent<ReflectionProbe>();
            probe.mode = UnityEngine.Rendering.ReflectionProbeMode.Baked;
            probe.size = bounds.size + Vector3.one;
            probe.boxProjection = true;
            probe.resolution = 128;
            Selection.activeGameObject = go;
            return "Added a baked reflection probe covering the whole map (128px, box projection). Bake lighting to fill it.";
        }

        internal static string Bake(bool final)
        {
            if (Lightmapping.isRunning)
                return "A bake is already running.";

            LightingSettings settings;
            try
            {
                settings = Lightmapping.lightingSettings;
            }
            catch (Exception)
            {
                settings = null;
            }

            if (settings == null)
            {
                settings = new LightingSettings { name = "World Lighting" };
                string folder = WPFMAWorldTypes.SceneFolder();
                WPFMAAvatarFolders.Ensure(folder);
                AssetDatabase.CreateAsset(settings, AssetDatabase.GenerateUniqueAssetPath(folder + "/Lighting Settings.lighting"));
                Lightmapping.lightingSettings = settings;
            }

            Undo.RecordObject(settings, "Lighting preset");
            settings.bakedGI = true;
            settings.realtimeGI = false;
            settings.lightmapper = LightingSettings.Lightmapper.ProgressiveGPU;
            settings.lightmapResolution = final ? 30f : 8f;
            settings.lightmapMaxSize = final ? 2048 : 1024;
            settings.lightmapPadding = final ? 4 : 2;
            settings.directSampleCount = final ? 64 : 16;
            settings.indirectSampleCount = final ? 512 : 64;
            settings.environmentSampleCount = final ? 256 : 64;
            settings.maxBounces = final ? 3 : 1;
            settings.filteringMode = LightingSettings.FilterMode.Auto;
            settings.lightmapCompression = LightmapCompression.NormalQuality;
            settings.directionalityMode = LightmapsMode.NonDirectional;
            EditorUtility.SetDirty(settings);

            Lightmapping.BakeAsync();
            return (final ? "Final" : "Preview") + " bake started. It runs in the background - watch the bar at the bottom right of Unity.";
        }
    }

    internal static class WPFMALightingSection
    {
        private const string PrefKey = "WPFMA.Tools.LightingExpanded";

        private static string status;
        private static float probeSpacing { get { return WPFMAToolDefaults.WorldProbeSpacing; } set { WPFMAToolDefaults.WorldProbeSpacing = value; } }
        private static bool probesInSelection;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Lighting helper", Lightmapping.isRunning ? "baking..." : (Lightmapping.lightingDataAsset != null ? "baked" : "not baked"), PrefKey, Body);
        }

        private static void DrawBakery()
        {
            var live = WPFMALightingHelper.LiveUnityLights();
            var baked = live.Where(WPFMALightingHelper.BakedByBakery).ToList();
            var unbaked = live.Except(baked).ToList();

            EditorGUILayout.Space(2f);
            EditorGUILayout.LabelField("Bakery", EditorStyles.miniBoldLabel);
            EditorGUILayout.LabelField(
                baked.Count == 0
                    ? "No Unity lights left on next to Bakery lights."
                    : baked.Count + " Unity light(s) are already baked by Bakery, but would still run as realtime lights in VRChat.",
                WPFMAToolSection.Hint(baked.Count > 0 ? WPFMAToolSection.WarnAmber : WPFMAToolSection.FaintText));
            using (new EditorGUI.DisabledScope(baked.Count == 0))
            {
                if (GUILayout.Button("Leave Bakery-baked lights out of VRChat"))
                    EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Lighting helper", "Leave Bakery-baked Unity lights out of VRChat", null, true, WPFMALightingHelper.LeaveOutBakedByBakery);
            }
            EditorGUILayout.LabelField(new GUIContent("Lights go EditorOnly; Bakery still bakes them.", "A light on its own object is tagged EditorOnly. A light sharing an object with something else (like a lamp model) is only switched off. Bakery keeps baking them."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            if (unbaked.Count > 0)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.LabelField(unbaked.Count + " Unity light(s) have no Bakery light, so Bakery won't bake them and they stay realtime.",
                        WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
                    if (GUILayout.Button("Select", EditorStyles.miniButton, GUILayout.Width(50f)))
                        Selection.objects = unbaked.Select(l => (UnityEngine.Object)l.gameObject).ToArray();
                }
            }
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Bake lighting the easy way.", "Baked lighting is the biggest performance win in a VRChat world. This marks what can be static, turns " + "realtime lights into baked ones, adds probes, and bakes with a preview or final preset."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            EditorGUILayout.LabelField("1. Static objects", EditorStyles.boldLabel);
            using (new EditorGUILayout.HorizontalScope())
            {
                if (GUILayout.Button("Mark the whole scene"))
                    EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Lighting helper", "Mark the whole scene static", null, true, () => WPFMALightingHelper.MarkStatic(false));
                if (GUILayout.Button("Mark selected"))
                    EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Lighting helper", "Mark selected static", null, true, () => WPFMALightingHelper.MarkStatic(true));
                if (GUILayout.Button("Clear selected"))
                    EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Lighting helper", "Clear static on selected", null, true, () => WPFMALightingHelper.ClearStatic());
            }
            EditorGUILayout.LabelField(new GUIContent("Skips anything that moves.", "Skips anything that moves: pickups, seats, Udon objects, mirrors, video players, animated and physics objects."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            EditorGUILayout.Space(4f);
            EditorGUILayout.LabelField("2. Lights", EditorStyles.boldLabel);
            var lights = UnityEngine.Object.FindObjectsOfType<Light>();
            int realtime = lights.Count(l => l.lightmapBakeType == LightmapBakeType.Realtime);
            EditorGUILayout.LabelField(lights.Length + " light(s), " + realtime + " realtime.", WPFMAToolSection.Hint(realtime > 1 ? WPFMAToolSection.WarnAmber : WPFMAToolSection.FaintText));
            using (new EditorGUILayout.HorizontalScope())
            {
                using (new EditorGUI.DisabledScope(realtime == 0))
                {
                    if (GUILayout.Button("Make realtime lights Baked"))
                        EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Lighting helper", "Make realtime lights Baked", null, true, () => WPFMALightingHelper.SetLights(LightmapBakeType.Baked));
                    if (GUILayout.Button("Make them Mixed"))
                        EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Lighting helper", "Make realtime lights Mixed", null, true, () => WPFMALightingHelper.SetLights(LightmapBakeType.Mixed));
                }
            }

            if (WPFMALightingHelper.BakeryInstalled)
                DrawBakery();

            EditorGUILayout.Space(4f);
            EditorGUILayout.LabelField("3. Probes", EditorStyles.boldLabel);
            using (new EditorGUILayout.HorizontalScope())
            {
                probeSpacing = EditorGUILayout.Slider("Light probe spacing (m)", probeSpacing, 0.5f, 10f);
            }
            probesInSelection = EditorGUILayout.ToggleLeft("Only around the selected objects", probesInSelection);
            using (new EditorGUILayout.HorizontalScope())
            {
                if (GUILayout.Button("Add light probe grid"))
                {
                    float spacing = probeSpacing;
                    bool selection = probesInSelection;
                    EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Lighting helper", "Add a light probe grid", null, true, () => WPFMALightingHelper.AddLightProbes(spacing, selection));
                }
                if (GUILayout.Button("Add reflection probe"))
                    EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Lighting helper", "Add a reflection probe", null, true, () => WPFMALightingHelper.AddReflectionProbe());
            }

            EditorGUILayout.Space(4f);
            EditorGUILayout.LabelField("4. Bake", EditorStyles.boldLabel);
            using (new EditorGUI.DisabledScope(Lightmapping.isRunning))
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    if (GUILayout.Button("Preview bake (fast)", GUILayout.Height(24f)))
                        EditorApplication.delayCall += () => status = WPFMALightingHelper.Bake(false);
                    if (GUILayout.Button("Final bake (slow, nice)", GUILayout.Height(24f)))
                        EditorApplication.delayCall += () => status = WPFMALightingHelper.Bake(true);
                }
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                if (Lightmapping.isRunning && GUILayout.Button("Cancel bake"))
                    Lightmapping.Cancel();
                using (new EditorGUI.DisabledScope(Lightmapping.isRunning))
                    if (GUILayout.Button("Clear baked data"))
                        EditorApplication.delayCall += () =>
                        {
                            if (EditorUtility.DisplayDialog("Clear baked lighting", "Remove the baked lighting from this scene?", "Clear", "Cancel"))
                            {
                                Lightmapping.Clear();
                                Lightmapping.ClearLightingDataAsset();
                                status = "Baked lighting cleared.";
                            }
                        };
            }

            var lightmaps = LightmapSettings.lightmaps;
            EditorGUILayout.LabelField(
                lightmaps.Length == 0 ? "No lightmaps yet." : lightmaps.Length + " lightmap(s).",
                WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

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