// 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 WPFMALightVolumes
    {
        internal const string VolumeType = "VRCLightVolumes.LightVolume";
        internal const string SetupType = "VRCLightVolumes.LightVolumeSetup";
        internal const string GitUrl = "https://github.com/REDSIM/VRCLightVolumes.git?path=/Packages/red.sim.lightvolumes";
        internal const string VpmListing = "https://redsim.github.io/vpmlisting/";
        internal const int MaxVolumes = 32;
        internal const float Overlap = 0.25f;

        internal static bool Installed
        {
            get { return WPFMAWorldTypes.Find(VolumeType) != null; }
        }

        internal static List<Component> Volumes()
        {
            return WPFMAWorldTypes.Objects(VolumeType);
        }

        internal static Component Setup()
        {
            return WPFMAWorldTypes.Objects(SetupType).FirstOrDefault();
        }

        internal static bool IsBaked(Component volume)
        {
            var texture = new SerializedObject(volume).FindProperty("Texture0");
            return texture != null && texture.objectReferenceValue != null;
        }

        internal static float VoxelsPerUnit(Component volume)
        {
            var density = new SerializedObject(volume).FindProperty("VoxelsPerUnit");
            return density != null ? density.floatValue : 3f;
        }

        internal static long EstimateBytes(Component volume)
        {
            var scale = volume.transform.lossyScale;
            float density = VoxelsPerUnit(volume);
            double voxels = Math.Max(1.0, Math.Abs(scale.x) * density) * Math.Max(1.0, Math.Abs(scale.y) * density) * Math.Max(1.0, Math.Abs(scale.z) * density);
            return (long)(voxels * 3 * 8);
        }

        internal static List<string> DuplicateNames()
        {
            return Volumes().GroupBy(v => v.gameObject.name).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
        }

        internal static string Install()
        {
            UnityEditor.PackageManager.Client.Add(GitUrl);
            return "Asked Unity's Package Manager to install VRC Light Volumes. It needs Git on this PC - if nothing happens, " +
                   "add the VPM listing " + VpmListing + " in the Creator Companion instead.";
        }

        internal static string AddVolume(Bounds bounds, string name)
        {
            var volumeType = WPFMAWorldTypes.Find(VolumeType);
            if (volumeType == null)
                return "VRC Light Volumes is not installed.";

            if (Volumes().Count >= MaxVolumes)
                return "This scene already has " + MaxVolumes + " light volumes - the most VRC Light Volumes shows at once.";

            Undo.SetCurrentGroupName("Add light volume");
            int group = Undo.GetCurrentGroup();

            EnsureSetup();

            var go = new GameObject(UniqueName("Light Volume - " + name));
            Undo.RegisterCreatedObjectUndo(go, "Add light volume");
            go.transform.position = bounds.center;
            go.transform.localScale = bounds.size + Vector3.one * (Overlap * 2f);

            var volume = Undo.AddComponent(go, volumeType);
            Call(volume, "SetupDependencies");

            Undo.CollapseUndoOperations(group);
            WPFMAWorldTypes.Invalidate();
            Selection.activeGameObject = go;
            return "Added '" + go.name + "' (" + Format(go.transform.localScale) + "), with " + Overlap + " m of overlap on every side.";
        }

        internal static void EnsureSetup()
        {
            if (Setup() != null)
                return;

            var setupType = WPFMAWorldTypes.Find(SetupType);
            if (setupType == null)
                return;

            var manager = new GameObject("Light Volume Manager");
            Undo.RegisterCreatedObjectUndo(manager, "Add light volume manager");
            var setup = Undo.AddComponent(manager, setupType);
            Call(setup, "SetupDependencies");
            WPFMAWorldTypes.Invalidate();
        }

        internal static string FixNames()
        {
            int renamed = 0;
            foreach (var group in Volumes().GroupBy(v => v.gameObject.name).Where(g => g.Count() > 1))
            {
                foreach (var volume in group.Skip(1))
                {
                    Undo.RecordObject(volume.gameObject, "Rename light volume");
                    volume.gameObject.name = UniqueName(volume.gameObject.name);
                    renamed++;
                }
            }
            WPFMAWorldTypes.Invalidate();
            return renamed == 0 ? "Every light volume already has its own name." : "Renamed " + renamed + " light volume(s) so each name is unique.";
        }

        internal static string SetDensity(float density)
        {
            var volumes = Volumes();
            foreach (var volume in volumes)
            {
                var serialized = new SerializedObject(volume);
                var property = serialized.FindProperty("VoxelsPerUnit");
                if (property == null)
                    continue;
                property.floatValue = density;
                serialized.ApplyModifiedProperties();
                Call(volume, "Recalculate");
            }
            return "Set " + volumes.Count + " volume(s) to " + density.ToString("0.#") + " voxels per metre. Bake again to apply.";
        }

        internal static void SetPreview(bool on)
        {
            foreach (var volume in Volumes())
            {
                var serialized = new SerializedObject(volume);
                var property = serialized.FindProperty("PreviewVoxels");
                if (property == null)
                    continue;
                property.boolValue = on;
                serialized.ApplyModifiedProperties();
            }
        }

        internal static string BakingMode(out bool canChange)
        {
            canChange = false;
            var setup = Setup();
            if (setup == null)
                return "no manager yet";

            var property = new SerializedObject(setup).FindProperty("BakingMode");
            if (property == null || property.propertyType != SerializedPropertyType.Enum)
                return "unknown";

            canChange = true;
            return property.enumDisplayNames[property.enumValueIndex];
        }

        internal static void SetBakingMode(string mode)
        {
            var setup = Setup();
            if (setup == null)
                return;

            var serialized = new SerializedObject(setup);
            var property = serialized.FindProperty("BakingMode");
            if (property == null || property.propertyType != SerializedPropertyType.Enum)
                return;

            int index = Array.IndexOf(property.enumNames, mode);
            if (index < 0)
                return;

            property.enumValueIndex = index;
            serialized.ApplyModifiedProperties();
        }

        private static string UniqueName(string wanted)
        {
            var taken = new HashSet<string>(Volumes().Select(v => v.gameObject.name));
            if (!taken.Contains(wanted))
                return wanted;
            for (int i = 2; i < 1000; i++)
            {
                string candidate = wanted + " " + i;
                if (!taken.Contains(candidate))
                    return candidate;
            }
            return wanted + " " + Guid.NewGuid().ToString("N").Substring(0, 4);
        }

        private static void Call(Component target, string method)
        {
            try
            {
                var info = target.GetType().GetMethod(method, Type.EmptyTypes);
                if (info != null)
                    info.Invoke(target, null);
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Light Volumes " + method + " failed: " + e.Message);
            }
        }

        internal static string Format(Vector3 size)
        {
            return size.x.ToString("0.#") + " x " + size.y.ToString("0.#") + " x " + size.z.ToString("0.#") + " m";
        }

        internal static Bounds? BoundsOf(IEnumerable<GameObject> objects)
        {
            Bounds? result = null;
            foreach (var renderer in objects.SelectMany(o => o.GetComponentsInChildren<Renderer>()))
            {
                if (renderer is ParticleSystemRenderer)
                    continue;
                if (result == null)
                    result = renderer.bounds;
                else
                {
                    var b = result.Value;
                    b.Encapsulate(renderer.bounds);
                    result = b;
                }
            }
            return result;
        }
    }

    internal static class WPFMALightVolumesSection
    {
        private const string PrefKey = "WPFMA.Tools.LightVolumesExpanded";
        private static readonly string[] DensityNames = { "Low (2)", "Normal (3)", "High (5)" };
        private static readonly float[] Densities = { 2f, 3f, 5f };

        private static bool perObject { get { return WPFMAToolDefaults.WorldVolumePerObject; } set { WPFMAToolDefaults.WorldVolumePerObject = value; } }
        private static bool preview;
        private static string status;

        internal static void Draw(GUIStyle sectionStyle)
        {
            string detail = !WPFMALightVolumes.Installed ? "not installed"
                : WPFMALightVolumes.Volumes().Count + " volume(s)";
            WPFMAToolSection.Draw(sectionStyle, "VRC Light Volumes", detail, PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Better avatar lighting in your world.", "VRC Light Volumes by RED_SIM replaces light probes with baked voxel lighting, so avatars and moving " + "props are lit properly by your world. Poiyomi and lilToon already support it. Free and MIT licensed."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            if (!WPFMALightVolumes.Installed)
            {
                EditorGUILayout.LabelField("Not installed in this project.", WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
                using (new EditorGUILayout.HorizontalScope())
                {
                    if (GUILayout.Button("Install VRC Light Volumes", GUILayout.Height(24f)))
                        EditorApplication.delayCall += () => status = WPFMALightVolumes.Install();
                    if (GUILayout.Button("Open its page", GUILayout.Width(110f), GUILayout.Height(24f)))
                        Application.OpenURL("https://github.com/REDSIM/VRCLightVolumes");
                }
                EditorGUILayout.LabelField("Installs from the official GitHub address through Unity's Package Manager (needs Git). " +
                                           "Or add " + WPFMALightVolumes.VpmListing + " to the Creator Companion.",
                    WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

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

            var volumes = WPFMALightVolumes.Volumes();
            int baked = volumes.Count(WPFMALightVolumes.IsBaked);
            long bytes = volumes.Sum(WPFMALightVolumes.EstimateBytes);
            var duplicates = WPFMALightVolumes.DuplicateNames();
            bool canChangeMode;
            string mode = WPFMALightVolumes.BakingMode(out canChangeMode);

            Line("Volumes", volumes.Count + " of " + WPFMALightVolumes.MaxVolumes + " max", volumes.Count <= WPFMALightVolumes.MaxVolumes);
            Line("Baked", volumes.Count == 0 ? "-" : baked + " of " + volumes.Count, volumes.Count == 0 || baked == volumes.Count);
            Line("Rough size", (bytes / (1024.0 * 1024.0)).ToString("0.0") + " MB", bytes < 40L * 1024 * 1024);
            Line("Manager", WPFMALightVolumes.Setup() != null ? "in the scene" : "added with the first volume", true);

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("Bakes with", GUILayout.Width(120f));
                EditorGUILayout.LabelField(mode, WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
                using (new EditorGUI.DisabledScope(!canChangeMode))
                {
                    if (GUILayout.Button("Unity", EditorStyles.miniButtonLeft, GUILayout.Width(60f)))
                        WPFMALightVolumes.SetBakingMode("Progressive");
                    if (GUILayout.Button("Bakery", EditorStyles.miniButtonRight, GUILayout.Width(60f)))
                        WPFMALightVolumes.SetBakingMode("Bakery");
                }
            }

            if (duplicates.Count > 0)
            {
                EditorGUILayout.LabelField("These names are used more than once, which breaks their baked textures: " + string.Join(", ", duplicates.ToArray()),
                    WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
                if (GUILayout.Button("Give each one its own name", EditorStyles.miniButton, GUILayout.Width(190f)))
                    EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("VRC Light Volumes", "Give each volume its own name", null, true, () => WPFMALightVolumes.FixNames());
            }

            EditorGUILayout.Space(6f);
            EditorGUILayout.LabelField("Add volumes", EditorStyles.boldLabel);
            var selected = Selection.gameObjects.Where(g => !EditorUtility.IsPersistent(g)).ToArray();
            perObject = EditorGUILayout.ToggleLeft(new GUIContent("One volume per selected object", "E.g. one per room."), perObject);

            using (new EditorGUI.DisabledScope(selected.Length == 0))
            {
                if (GUILayout.Button(selected.Length == 0 ? "Select rooms or areas first" : "Add volume(s) around the selection", GUILayout.Height(24f)))
                {
                    var chosen = selected;
                    bool each = perObject;
                    EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("VRC Light Volumes", "Add volume(s) around the selection", null, true, () => AddAround(chosen, each));
                }
            }

            if (GUILayout.Button("Add one volume around the whole map", EditorStyles.miniButton))
                EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("VRC Light Volumes", "Add a volume around the map", null, true, () => WPFMALightVolumes.AddVolume(WPFMAWorldTypes.SceneBounds(), "Map"));

            EditorGUILayout.LabelField("Each volume overlaps its neighbours by " + WPFMALightVolumes.Overlap + " m to hide seams. Fine-tune with Edit Bounds on the volume.",
                WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            EditorGUILayout.Space(6f);
            EditorGUILayout.LabelField("Quality", EditorStyles.boldLabel);
            using (new EditorGUILayout.HorizontalScope())
            {
                for (int i = 0; i < Densities.Length; i++)
                {
                    using (new EditorGUI.DisabledScope(volumes.Count == 0))
                    {
                        if (GUILayout.Button(DensityNames[i]))
                        {
                            float density = Densities[i];
                            EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("VRC Light Volumes", "Set voxel density to " + density, null, true, () => WPFMALightVolumes.SetDensity(density));
                        }
                    }
                }
            }
            EditorGUILayout.LabelField(new GUIContent("Voxels per metre.", "Voxels per metre for every volume. Doubling it makes the baked files about 8 times bigger."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            bool nowPreview = EditorGUILayout.ToggleLeft("Show the voxels in the Scene view", preview);
            if (nowPreview != preview)
            {
                preview = nowPreview;
                WPFMALightVolumes.SetPreview(preview);
            }

            EditorGUILayout.Space(6f);
            EditorGUILayout.LabelField(new GUIContent("Bakes with the scene's lighting.", "Light volumes bake together with the scene's lighting - use the Lighting helper's bake buttons above. " + "Bakery is recommended by RED_SIM for speed and quality."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

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

        private static string AddAround(GameObject[] objects, bool each)
        {
            if (!each)
            {
                var bounds = WPFMALightVolumes.BoundsOf(objects);
                return bounds == null ? "The selection has nothing visible to size a volume from." : WPFMALightVolumes.AddVolume(bounds.Value, objects[0].name);
            }

            var notes = new List<string>();
            foreach (var go in objects)
            {
                var bounds = WPFMALightVolumes.BoundsOf(new[] { go });
                if (bounds != null)
                    notes.Add(WPFMALightVolumes.AddVolume(bounds.Value, go.name));
            }
            return notes.Count == 0 ? "The selection has nothing visible to size a volume from." : "Added " + notes.Count + " volume(s). " + notes.Last();
        }

        private static void Line(string label, string value, bool ok)
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField(label, GUILayout.Width(120f));
                EditorGUILayout.LabelField(value, WPFMAToolSection.Hint(ok ? WPFMAToolSection.OkGreen : WPFMAToolSection.WarnAmber));
            }
        }
    }
}
#endif
