// 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 WPFMAWorldSetup
    {
        internal const string PostProcessingLayerName = "PostProcessing";

        internal static string AddDescriptor()
        {
            if (WPFMAWorldTypes.Descriptor() != null)
                return "The scene already has a Scene Descriptor.";

            string prefab = WPFMAWorldTypes.SdkPrefab("VRCWorld.prefab");
            GameObject world;

            if (prefab != null)
            {
                world = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<GameObject>(prefab));
                world.transform.position = Vector3.zero;
            }
            else
            {
                var type = WPFMAWorldTypes.Find(WPFMAWorldTypes.SceneDescriptor);
                if (type == null)
                    return "The world SDK is not installed.";

                world = new GameObject("VRCWorld");
                world.AddComponent(type);
            }

            Undo.RegisterCreatedObjectUndo(world, "Add VRCWorld");
            Selection.activeGameObject = world;
            return "Added VRCWorld. It holds the Scene Descriptor and the upload ID.";
        }

        internal static string AddSpawn()
        {
            var descriptor = WPFMAWorldTypes.Descriptor();
            if (descriptor == null)
                return "Add the Scene Descriptor first.";

            var serialized = new SerializedObject(descriptor);
            var spawns = serialized.FindProperty("spawns");
            if (spawns == null)
                return "Could not find the spawn list on the descriptor.";

            var spawn = new GameObject("Spawn " + (spawns.arraySize + 1));
            Undo.RegisterCreatedObjectUndo(spawn, "Add spawn");
            spawn.transform.position = WPFMAWorldTypes.PlacementPoint();

            var view = SceneView.lastActiveSceneView;
            if (view != null)
            {
                var forward = view.rotation * Vector3.forward;
                forward.y = 0f;
                if (forward.sqrMagnitude > 0.001f)
                    spawn.transform.rotation = Quaternion.LookRotation(forward.normalized, Vector3.up);
            }

            for (int i = spawns.arraySize - 1; i >= 0; i--)
            {
                if (spawns.GetArrayElementAtIndex(i).objectReferenceValue == null)
                    spawns.DeleteArrayElementAtIndex(i);
            }

            spawns.InsertArrayElementAtIndex(spawns.arraySize);
            spawns.GetArrayElementAtIndex(spawns.arraySize - 1).objectReferenceValue = spawn.transform;
            serialized.ApplyModifiedProperties();

            Selection.activeGameObject = spawn;
            return "Added '" + spawn.name + "' where the Scene view is looking, facing the same way.";
        }

        internal static string SetRespawnHeight()
        {
            var descriptor = WPFMAWorldTypes.Descriptor();
            if (descriptor == null)
                return "Add the Scene Descriptor first.";

            var bounds = WPFMAWorldTypes.SceneBounds();
            float height = Mathf.Floor(bounds.min.y - 10f);

            var serialized = new SerializedObject(descriptor);
            var property = serialized.FindProperty("RespawnHeightY");
            if (property == null)
                return "Could not find the respawn height on the descriptor.";

            property.floatValue = height;
            serialized.ApplyModifiedProperties();
            return "Respawn height set to " + height + " (10 m below the lowest part of the map).";
        }

        internal static string AddReferenceCamera(bool postProcessing)
        {
            var descriptor = WPFMAWorldTypes.Descriptor();
            if (descriptor == null)
                return "Add the Scene Descriptor first.";

            var serialized = new SerializedObject(descriptor);
            var property = serialized.FindProperty("ReferenceCamera");
            if (property == null)
                return "Could not find the reference camera slot on the descriptor.";

            var existing = property.objectReferenceValue as GameObject;
            var cameraObject = existing;

            if (cameraObject == null)
            {
                cameraObject = new GameObject("Reference Camera");
                Undo.RegisterCreatedObjectUndo(cameraObject, "Add reference camera");
                cameraObject.transform.SetParent(descriptor.transform, false);

                var camera = cameraObject.AddComponent<Camera>();
                camera.nearClipPlane = 0.01f;
                camera.farClipPlane = 1000f;
                camera.enabled = false;

                property.objectReferenceValue = cameraObject;
                serialized.ApplyModifiedProperties();
            }

            string note = existing == null
                ? "Added a reference camera (near clip 0.01 so close-up avatars are not cut off). Its Camera is switched off - VRChat only copies its settings."
                : "The descriptor already has a reference camera.";

            if (postProcessing)
                note += " " + AddPostProcessing(cameraObject);

            Selection.activeGameObject = cameraObject;
            return note;
        }

        internal static bool PostProcessingAvailable
        {
            get { return WPFMAWorldTypes.Find("UnityEngine.Rendering.PostProcessing.PostProcessLayer") != null; }
        }

        private static string AddPostProcessing(GameObject cameraObject)
        {
            var layerType = WPFMAWorldTypes.Find("UnityEngine.Rendering.PostProcessing.PostProcessLayer");
            var volumeType = WPFMAWorldTypes.Find("UnityEngine.Rendering.PostProcessing.PostProcessVolume");
            var profileType = WPFMAWorldTypes.Find("UnityEngine.Rendering.PostProcessing.PostProcessProfile");
            var bloomType = WPFMAWorldTypes.Find("UnityEngine.Rendering.PostProcessing.Bloom");
            var gradingType = WPFMAWorldTypes.Find("UnityEngine.Rendering.PostProcessing.ColorGrading");

            if (layerType == null || volumeType == null || profileType == null)
                return "Post-processing was skipped: the Post Processing package is not installed.";

            try
            {
                int layer = EnsureLayer(PostProcessingLayerName);
                if (layer < 0)
                    return "Post-processing was skipped: there is no free layer to use for it.";

                var ppLayer = cameraObject.GetComponent(layerType);
                if (ppLayer == null)
                    ppLayer = Undo.AddComponent(cameraObject, layerType);
                var layerSerialized = new SerializedObject(ppLayer);
                var mask = layerSerialized.FindProperty("volumeLayer");
                if (mask != null)
                    mask.intValue = 1 << layer;
                var trigger = layerSerialized.FindProperty("volumeTrigger");
                if (trigger != null)
                    trigger.objectReferenceValue = cameraObject.transform;
                var resources = layerSerialized.FindProperty("m_Resources");
                if (resources != null && resources.objectReferenceValue == null)
                {
                    var guid = AssetDatabase.FindAssets("t:PostProcessResources").FirstOrDefault();
                    if (guid != null)
                        resources.objectReferenceValue = AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(guid));
                }
                layerSerialized.ApplyModifiedProperties();

                var existingVolume = UnityEngine.Object.FindObjectsOfType(volumeType, true).OfType<Component>()
                    .FirstOrDefault(c => c.gameObject.scene.IsValid());
                if (existingVolume != null)
                    return "Post-processing camera set up; the scene already has a volume ('" + existingVolume.name + "').";

                string folder = WPFMAWorldTypes.SceneFolder();
                WPFMAAvatarFolders.Ensure(folder);

                var profile = ScriptableObject.CreateInstance(profileType);
                string path = AssetDatabase.GenerateUniqueAssetPath(folder + "/Post Processing.asset");
                AssetDatabase.CreateAsset(profile, path);

                var addSettings = profileType.GetMethod("AddSettings", new[] { typeof(Type) });
                if (addSettings != null)
                {
                    if (bloomType != null)
                    {
                        var bloom = addSettings.Invoke(profile, new object[] { bloomType });
                        Override(bloom, "intensity", 0.6f);
                        Override(bloom, "threshold", 1.1f);
                        AssetDatabase.AddObjectToAsset((UnityEngine.Object)bloom, profile);
                    }

                    if (gradingType != null)
                    {
                        var grading = addSettings.Invoke(profile, new object[] { gradingType });
                        var tonemapperField = gradingType.GetField("tonemapper");
                        if (tonemapperField != null)
                        {
                            var parameter = tonemapperField.GetValue(grading);
                            var enumType = parameter.GetType().BaseType != null && parameter.GetType().BaseType.IsGenericType
                                ? parameter.GetType().BaseType.GetGenericArguments()[0]
                                : null;
                            if (enumType != null && enumType.IsEnum)
                                Override(grading, "tonemapper", Enum.Parse(enumType, "Neutral"));
                        }
                        AssetDatabase.AddObjectToAsset((UnityEngine.Object)grading, profile);
                    }
                }

                EditorUtility.SetDirty(profile);
                AssetDatabase.SaveAssets();

                var volumeObject = new GameObject("Post Processing Volume") { layer = layer };
                Undo.RegisterCreatedObjectUndo(volumeObject, "Add post-processing");
                var volume = volumeObject.AddComponent(volumeType);
                var volumeSerialized = new SerializedObject(volume);
                var global = volumeSerialized.FindProperty("isGlobal");
                if (global != null)
                    global.boolValue = true;
                var shared = volumeSerialized.FindProperty("sharedProfile");
                if (shared != null)
                    shared.objectReferenceValue = profile;
                volumeSerialized.ApplyModifiedProperties();

                return "Post-processing added: a global volume on the '" + PostProcessingLayerName + "' layer with light bloom and " +
                       "neutral tonemapping (" + path + ").";
            }
            catch (Exception e)
            {
                return "Post-processing could not be set up: " + e.Message;
            }
        }

        private static void Override(object settings, string field, object value)
        {
            if (settings == null)
                return;

            var info = settings.GetType().GetField(field);
            var parameter = info != null ? info.GetValue(settings) : null;
            if (parameter == null)
                return;

            var method = parameter.GetType().GetMethods().FirstOrDefault(m => m.Name == "Override" && m.GetParameters().Length == 1);
            if (method != null)
                method.Invoke(parameter, new[] { value });
        }

        internal static int EnsureLayer(string name)
        {
            int existing = LayerMask.NameToLayer(name);
            if (existing >= 0)
                return existing;

            var assets = AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset");
            if (assets == null || assets.Length == 0)
                return -1;

            var tagManager = new SerializedObject(assets[0]);
            var layers = tagManager.FindProperty("layers");
            if (layers == null)
                return -1;

            for (int i = 22; i < 32 && i < layers.arraySize; i++)
            {
                var slot = layers.GetArrayElementAtIndex(i);
                if (string.IsNullOrEmpty(slot.stringValue))
                {
                    slot.stringValue = name;
                    tagManager.ApplyModifiedProperties();
                    return i;
                }
            }

            return -1;
        }
    }

    internal static class WPFMAWorldSetupSection
    {
        private const string PrefKey = "WPFMA.Tools.WorldSetupExpanded";

        private static string status;
        private static bool postProcessing { get { return WPFMAToolDefaults.WorldPostProcessing; } set { WPFMAToolDefaults.WorldPostProcessing = value; } }

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "World setup", Detail(), PrefKey, Body);
        }

        private static string Detail()
        {
            if (!WPFMAWorldTypes.WorldSdkInstalled)
                return "needs the world SDK";
            return WPFMAWorldTypes.Descriptor() != null ? "descriptor found" : "no descriptor yet";
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Make the scene an uploadable world.", "Turns an empty scene into an uploadable world: the Scene Descriptor, spawn points, a respawn height " + "under the map, and a reference camera with optional post-processing."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            if (!WPFMAWorldTypes.WorldSdkInstalled)
            {
                WPFMAWorldTypes.NeedsWorldSdk();
                return;
            }

            var descriptor = WPFMAWorldTypes.Descriptor();
            SerializedObject serialized = descriptor != null ? new SerializedObject(descriptor) : null;

            Row("Scene Descriptor", descriptor != null ? descriptor.name : "missing", descriptor != null,
                descriptor == null ? "Add VRCWorld" : null, () => status = WPFMAWorldSetup.AddDescriptor());

            int spawns = 0;
            var spawnList = serialized != null ? serialized.FindProperty("spawns") : null;
            if (spawnList != null)
                for (int i = 0; i < spawnList.arraySize; i++)
                    if (spawnList.GetArrayElementAtIndex(i).objectReferenceValue != null)
                        spawns++;

            Row("Spawn points", descriptor == null ? "-" : spawns == 0 ? "none (players spawn at the descriptor)" : spawns.ToString(),
                spawns > 0, descriptor != null ? "Add at the Scene view" : null, () => status = WPFMAWorldSetup.AddSpawn());

            var respawn = serialized != null ? serialized.FindProperty("RespawnHeightY") : null;
            float lowest = WPFMAWorldTypes.SceneBounds().min.y;
            bool respawnOk = respawn != null && respawn.floatValue < lowest;
            Row("Respawn height", respawn == null ? "-" : respawn.floatValue.ToString("0.#") + (respawnOk ? "" : "  (above part of the map!)"),
                respawnOk, descriptor != null ? "Put it under the map" : null, () => status = WPFMAWorldSetup.SetRespawnHeight());

            var reference = serialized != null ? serialized.FindProperty("ReferenceCamera") : null;
            bool hasReference = reference != null && reference.objectReferenceValue != null;
            Row("Reference camera", hasReference ? reference.objectReferenceValue.name : "none", hasReference,
                descriptor != null ? (hasReference ? "Set up post-processing" : "Add one") : null,
                () => status = WPFMAWorldSetup.AddReferenceCamera(postProcessing));

            using (new EditorGUI.DisabledScope(!WPFMAWorldSetup.PostProcessingAvailable))
            {
                postProcessing = EditorGUILayout.ToggleLeft(
                    WPFMAWorldSetup.PostProcessingAvailable
                        ? "Include post-processing (light bloom, neutral tonemapping)"
                        : "Include post-processing (install the Post Processing package first)",
                    postProcessing && WPFMAWorldSetup.PostProcessingAvailable);
            }

            EditorGUILayout.LabelField(new GUIContent("Adds a post-processing layer if needed.",
                "Post-processing uses a '" + WPFMAWorldSetup.PostProcessingLayerName + "' layer; one is added to the project if it does not exist."),
                WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

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

        private static void Row(string label, string value, bool ok, string button, Action action)
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField(label, GUILayout.Width(120f));
                EditorGUILayout.LabelField(value, WPFMAToolSection.Hint(ok ? WPFMAToolSection.OkGreen : WPFMAToolSection.WarnAmber));
                if (button != null && GUILayout.Button(button, EditorStyles.miniButton, GUILayout.Width(150f)))
                    EditorApplication.delayCall += () => WPFMAChangeLog.Run("World setup", button, null, true, () => { action(); return status; });
            }
        }
    }

    internal static class WPFMAWorldPrefabsSection
    {
        private const string PrefKey = "WPFMA.Tools.WorldPrefabsExpanded";

        private sealed class Entry
        {
            public string Label;
            public string File;
            public string Hint;
        }

        private static readonly Entry[] Entries =
        {
            new Entry { Label = "Mirror", File = "VRCMirror.prefab", Hint = "VRChat's mirror. Placed switched off - VRChat recommends mirrors are off by default." },
            new Entry { Label = "Chair", File = "VRCChair3.prefab", Hint = "A seat players can click to sit in." },
            new Entry { Label = "Avatar pedestal", File = "AvatarPedestal.prefab", Hint = "Lets players switch into an avatar you choose." },
            new Entry { Label = "Video player", File = "UdonSyncPlayer (Unity).prefab", Hint = "Synced video player for normal video links." },
            new Entry { Label = "Video player (streams)", File = "UdonSyncPlayer (AVPro).prefab", Hint = "Synced AVPro player - also plays livestreams." },
            new Entry { Label = "Portal marker", File = "VRCPortalMarker.prefab", Hint = "A fixed portal to another world." },
            new Entry { Label = "Pens", File = "SimplePenSystem.prefab", Hint = "Simple synced pens for drawing in the air." }
        };

        private static string status;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Quick prefabs", WPFMAWorldTypes.WorldSdkInstalled ? "VRChat SDK prefabs" : "needs the world SDK", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("VRChat's ready-made prefabs.", "Drops VRChat's own ready-made prefabs from the world SDK into the scene, where the Scene view is looking."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            if (!WPFMAWorldTypes.WorldSdkInstalled)
            {
                WPFMAWorldTypes.NeedsWorldSdk();
                return;
            }

            foreach (var entry in Entries)
            {
                string path = WPFMAWorldTypes.SdkPrefab(entry.File);
                using (new EditorGUILayout.HorizontalScope())
                {
                    using (new EditorGUI.DisabledScope(path == null))
                    {
                        if (GUILayout.Button(entry.Label, GUILayout.Width(160f)))
                        {
                            var chosen = entry;
                            var prefabPath = path;
                            EditorApplication.delayCall += () => WPFMAChangeLog.Run("Quick prefabs", "Add " + chosen.Label, null, true, () => { Place(chosen, prefabPath); return status; });
                        }
                    }

                    EditorGUILayout.LabelField(path == null ? "not found in this SDK version" : entry.Hint,
                        WPFMAToolSection.Hint(path == null ? WPFMAToolSection.WarnAmber : WPFMAToolSection.FaintText));
                }
            }

            var mirrors = WPFMAWorldTypes.Objects(WPFMAWorldTypes.Mirror);
            int videos = WPFMAWorldTypes.Objects(WPFMAWorldTypes.UnityVideo).Count + WPFMAWorldTypes.Objects(WPFMAWorldTypes.AVProVideo).Count;
            if (mirrors.Count > 1 || videos > 2)
            {
                EditorGUILayout.LabelField(
                    "This scene has " + mirrors.Count + " mirror(s) and " + videos + " video player(s). VRChat recommends at most one " +
                    "mirror and two video players per room.",
                    WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
            }

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

        private static void Place(Entry entry, string path)
        {
            var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            if (prefab == null)
                return;

            var instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
            Undo.RegisterCreatedObjectUndo(instance, "Add " + entry.Label);
            instance.transform.position = WPFMAWorldTypes.PlacementPoint();

            if (entry.File == "VRCMirror.prefab")
                instance.SetActive(false);

            Selection.activeGameObject = instance;
            status = "Added " + entry.Label + (entry.File == "VRCMirror.prefab" ? " (switched off - turn it on with a toggle or button)." : ".");
        }
    }
}
#endif
