// 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.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace WPFMA
{
    internal static class WPFMAOcclusionSection
    {
        private const string PrefKey = "WPFMA.Tools.OcclusionExpanded";

        private static string status;
        private static float smallestOccluder { get { return WPFMAToolDefaults.WorldSmallestOccluder; } set { WPFMAToolDefaults.WorldSmallestOccluder = value; } }
        private static float smallestHole { get { return WPFMAToolDefaults.WorldSmallestHole; } set { WPFMAToolDefaults.WorldSmallestHole = value; } }
        private static int occluders;
        private static double occludersAt = -10;

        internal static void Draw(GUIStyle sectionStyle)
        {
            string detail = StaticOcclusionCulling.isRunning ? "baking..."
                : StaticOcclusionCulling.umbraDataSize > 0 ? "baked"
                : "not baked";
            WPFMAToolSection.Draw(sectionStyle, "Occlusion culling", detail, PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Hide what's behind walls.", "Stops VRChat drawing things hidden behind walls. Mark the scene static (Lighting page), add blocker " + "boxes between areas that cannot see each other, then bake."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            double now = EditorApplication.timeSinceStartup;
            if (now - occludersAt > 1.5 || now < occludersAt)
            {
                occluders = Object.FindObjectsOfType<MeshRenderer>()
                    .Count(r => GameObjectUtility.GetStaticEditorFlags(r.gameObject).HasFlag(StaticEditorFlags.OccluderStatic));
                occludersAt = now;
            }
            EditorGUILayout.LabelField(occluders + " object(s) are marked as occluders.",
                WPFMAToolSection.Hint(occluders == 0 ? WPFMAToolSection.WarnAmber : WPFMAToolSection.FaintText));

            if (occluders == 0 && GUILayout.Button("Mark the scene static first", EditorStyles.miniButton, GUILayout.Width(200f)))
                EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Occlusion culling", "Mark the scene static", null, true, () => WPFMALightingHelper.MarkStatic(false));

            EditorGUILayout.Space(4f);
            if (GUILayout.Button("Add a blocker box where the Scene view is looking"))
                EditorApplication.delayCall += () => WPFMAChangeLog.Run("Occlusion culling", "Add a blocker box", null, true, () => { AddBlocker(); return status; });
            EditorGUILayout.LabelField(new GUIContent("Invisible blocker, left out of the upload.", "An invisible box, tagged EditorOnly so it is removed from the upload, that still blocks sight while baking. " + "Stretch it to fill walls between rooms."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            EditorGUILayout.Space(4f);
            smallestOccluder = EditorGUILayout.Slider("Smallest occluder (m)", smallestOccluder, 0.5f, 10f);
            smallestHole = EditorGUILayout.Slider("Smallest hole (m)", smallestHole, 0.05f, 2f);

            using (new EditorGUILayout.HorizontalScope())
            {
                using (new EditorGUI.DisabledScope(StaticOcclusionCulling.isRunning))
                {
                    if (GUILayout.Button("Bake occlusion", GUILayout.Height(24f)))
                    {
                        float occluder = smallestOccluder, hole = smallestHole;
                        EditorApplication.delayCall += () =>
                        {
                            StaticOcclusionCulling.smallestOccluder = occluder;
                            StaticOcclusionCulling.smallestHole = hole;
                            StaticOcclusionCulling.backfaceThreshold = 100f;
                            status = StaticOcclusionCulling.GenerateInBackground()
                                ? "Occlusion bake started in the background."
                                : "Unity could not start the occlusion bake.";
                        };
                    }
                }

                if (StaticOcclusionCulling.isRunning && GUILayout.Button("Cancel", GUILayout.Height(24f)))
                    StaticOcclusionCulling.Cancel();

                using (new EditorGUI.DisabledScope(StaticOcclusionCulling.isRunning || StaticOcclusionCulling.umbraDataSize == 0))
                {
                    if (GUILayout.Button("Clear", GUILayout.Height(24f), GUILayout.Width(60f)))
                    {
                        StaticOcclusionCulling.Clear();
                        status = "Occlusion data cleared.";
                    }
                }
            }

            EditorGUILayout.LabelField(new GUIContent("Smaller hides more but bakes slower.", "Smallest occluder: bigger bakes faster with less data; smaller hides more. Smallest hole: gaps smaller than " + "this count as solid."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

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

        private static void AddBlocker()
        {
            var box = GameObject.CreatePrimitive(PrimitiveType.Cube);
            box.name = "Occlusion Blocker";
            Undo.RegisterCreatedObjectUndo(box, "Add occlusion blocker");

            Object.DestroyImmediate(box.GetComponent<Collider>());
            box.tag = "EditorOnly";
            box.transform.position = WPFMAWorldTypes.PlacementPoint() + Vector3.up * 1.5f;
            box.transform.localScale = new Vector3(4f, 3f, 0.3f);

            var renderer = box.GetComponent<MeshRenderer>();
            renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            renderer.receiveShadows = false;
            GameObjectUtility.SetStaticEditorFlags(box, StaticEditorFlags.OccluderStatic);

            Selection.activeGameObject = box;
            status = "Added a blocker box. It is EditorOnly, so it never reaches the upload.";
        }
    }

    internal static class WPFMAEditorOnlySection
    {
        private const string PrefKey = "WPFMA.Tools.EditorOnlyExpanded";

        private static string status;
        private static List<GameObject> tagged = new List<GameObject>();
        private static double taggedAt = -10;

        private static List<GameObject> Tagged()
        {
            double now = EditorApplication.timeSinceStartup;
            if (now - taggedAt > 1.5 || now < taggedAt || tagged.Any(g => g == null))
            {
                tagged = WPFMAWorldTypes.SceneObjects().Where(g => g.CompareTag("EditorOnly")).ToList();
                taggedAt = now;
            }
            return tagged;
        }

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Editor-only objects", Tagged().Count + " in the scene", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("EditorOnly stays out of the upload.", "Objects tagged EditorOnly stay in Unity but are left out of the upload - handy for reference models, " + "notes, occlusion blockers and test props."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            var selected = Selection.gameObjects.Where(g => !EditorUtility.IsPersistent(g)).ToArray();

            using (new EditorGUILayout.HorizontalScope())
            {
                using (new EditorGUI.DisabledScope(selected.Length == 0))
                {
                    if (GUILayout.Button("Leave selected out of the upload"))
                        EditorApplication.delayCall += () => WPFMAChangeLog.Run("Editor-only objects", "Leave " + selected.Length + " object(s) out of the upload", null, true, () => { Tag(selected, "EditorOnly"); return status; });
                    if (GUILayout.Button("Put selected back in"))
                        EditorApplication.delayCall += () => WPFMAChangeLog.Run("Editor-only objects", "Put " + selected.Length + " object(s) back in the upload", null, true, () => { Tag(selected, "Untagged"); return status; });
                }
            }

            var tagged = Tagged();
            if (tagged.Count > 0)
            {
                EditorGUILayout.Space(2f);
                foreach (var go in tagged.Take(20))
                {
                    using (new EditorGUILayout.HorizontalScope())
                    {
                        EditorGUILayout.LabelField(go.name, WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
                        if (GUILayout.Button("Select", EditorStyles.miniButton, GUILayout.Width(55f)))
                            Selection.activeGameObject = go;
                    }
                }
                if (tagged.Count > 20)
                    EditorGUILayout.LabelField("and " + (tagged.Count - 20) + " more", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            }

            EditorGUILayout.LabelField("Everything under an EditorOnly object is left out too.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

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

        private static void Tag(GameObject[] objects, string tag)
        {
            Undo.RecordObjects(objects.Cast<Object>().ToArray(), "Change tag");
            foreach (var go in objects)
                if (go != null)
                    go.tag = tag;
            taggedAt = -10;
            status = (tag == "EditorOnly" ? "Left out of the upload: " : "Back in the upload: ") + objects.Length + " object(s).";
        }
    }
}
#endif
