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

namespace WPFMA
{
    internal static class WPFMATeleportSection
    {
        private const string PrefKey = "WPFMA.Tools.TeleportExpanded";
        private const string Script = "WPFMA.Udon.WPFMATeleport";

        private static Transform destination;
        private static bool walkIn { get { return WPFMAToolDefaults.WorldTeleportWalkIn; } set { WPFMAToolDefaults.WorldTeleportWalkIn = value; } }
        private static bool twoWay { get { return WPFMAToolDefaults.WorldTeleportTwoWay; } set { WPFMAToolDefaults.WorldTeleportTwoWay = value; } }
        private static string status;
        private static bool statusIsError;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Teleport maker", WPFMAUdonBridge.Available ? "move players around the map" : "needs UdonSharp", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("A pad that moves the player.", "A pad or button that moves the player to another spot in the world. For a portal to a different " + "world, use the Portal marker in Quick prefabs."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            if (!WPFMAUdonBridge.Available)
            {
                WPFMAUdonBridge.NeedsUdonSharp();
                return;
            }

            EditorGUILayout.LabelField("1. Where it goes", EditorStyles.boldLabel);
            using (new EditorGUILayout.HorizontalScope())
            {
                destination = (Transform)EditorGUILayout.ObjectField(destination, typeof(Transform), true);
                if (GUILayout.Button("Add where the Scene view is looking", EditorStyles.miniButton, GUILayout.Width(220f)))
                    EditorApplication.delayCall += () => destination = Marker("Teleport Destination", WPFMAWorldTypes.PlacementPoint());
            }
            if (destination != null && EditorUtility.IsPersistent(destination))
                destination = null;
            EditorGUILayout.LabelField(new GUIContent("Players face the blue arrow.", "Players arrive facing the destination's blue (forward) arrow."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            EditorGUILayout.Space(4f);
            EditorGUILayout.LabelField("2. What sends them", EditorStyles.boldLabel);
            walkIn = EditorGUILayout.ToggleLeft("Step onto it (otherwise players click it)", walkIn);
            twoWay = EditorGUILayout.ToggleLeft("Two-way: add a pad at the destination that comes back", twoWay);

            var selected = Selection.gameObjects.Where(g => !EditorUtility.IsPersistent(g) && (destination == null || g != destination.gameObject)).ToArray();

            using (new EditorGUI.DisabledScope(destination == null))
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    if (GUILayout.Button("Make a pad where the Scene view is looking", GUILayout.Height(24f)))
                        EditorApplication.delayCall += () => WPFMAChangeLog.Run("Teleport maker", "Make a teleport pad", null, true, () => { Make(null); return status; });

                    using (new EditorGUI.DisabledScope(selected.Length != 1))
                        if (GUILayout.Button(selected.Length == 1 ? "Use '" + selected[0].name + "'" : "Use selected", GUILayout.Height(24f)))
                        {
                            var source = selected[0];
                            EditorApplication.delayCall += () => WPFMAChangeLog.Run("Teleport maker", "Make '" + source.name + "' a teleport", null, true, () => { Make(source); return status; });
                        }
                }
            }

            if (destination == null)
                EditorGUILayout.LabelField("Set the destination first.", WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));

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

        private static Transform Marker(string name, Vector3 position)
        {
            var go = new GameObject(name);
            Undo.RegisterCreatedObjectUndo(go, "Add teleport destination");
            go.transform.position = position;

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

            Selection.activeGameObject = go;
            return go.transform;
        }

        private static GameObject Pad(string name, Vector3 position)
        {
            var pad = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
            pad.name = name;
            Undo.RegisterCreatedObjectUndo(pad, "Make teleport");
            UnityEngine.Object.DestroyImmediate(pad.GetComponent<Collider>());
            pad.transform.position = position + Vector3.up * 0.03f;
            pad.transform.localScale = new Vector3(1.2f, 0.03f, 1.2f);
            return pad;
        }

        private static void Make(GameObject source)
        {
            Undo.SetCurrentGroupName("Make teleport");
            int group = Undo.GetCurrentGroup();

            var sender = source != null ? source : Pad("Teleport Pad", WPFMAWorldTypes.PlacementPoint());
            string problem;
            if (!Hook(sender, destination, out problem))
            {
                status = problem;
                statusIsError = true;
                Undo.CollapseUndoOperations(group);
                return;
            }

            if (twoWay)
            {
                var back = Marker("Teleport Return Point", sender.transform.position + sender.transform.forward * 1.5f);
                var returnPad = Pad("Teleport Pad (back)", destination.position + destination.forward * 2f);
                Hook(returnPad, back, out problem);
            }

            Undo.CollapseUndoOperations(group);
            Selection.activeGameObject = sender;
            status = "Teleport made" + (twoWay ? " both ways" : string.Empty) + ". " + (walkIn ? "Players step onto it." : "Players click it.");
            statusIsError = false;
        }

        private static bool Hook(GameObject sender, Transform target, out string problem)
        {
            if (walkIn)
            {
                var trigger = sender.GetComponents<Collider>().FirstOrDefault(c => c.isTrigger);
                if (trigger == null)
                {
                    var box = Undo.AddComponent<BoxCollider>(sender);
                    box.isTrigger = true;
                    var scale = sender.transform.lossyScale;
                    float height = 2f / Mathf.Max(0.001f, Mathf.Abs(scale.y));
                    box.size = new Vector3(box.size.x, height, box.size.z);
                    box.center = new Vector3(box.center.x, height * 0.5f, box.center.z);
                }
            }
            else if (sender.GetComponent<Collider>() == null)
            {
                Undo.AddComponent<BoxCollider>(sender);
            }

            var proxy = WPFMAUdonBridge.Add(sender, Script, out problem);
            if (proxy == null)
                return false;

            WPFMAUdonBridge.Set(proxy, "destination", target);
            WPFMAUdonBridge.Set(proxy, "onTouch", walkIn);
            WPFMAUdonBridge.Commit(proxy, walkIn ? null : "Teleport");
            return true;
        }
    }

    internal static class WPFMASeatSection
    {
        private const string PrefKey = "WPFMA.Tools.SeatExpanded";
        private const string Script = "WPFMA.Udon.WPFMASeat";
        private const string Station = "VRC.SDK3.Components.VRCStation";

        private static bool flip;
        private static float seatHeight { get { return WPFMAToolDefaults.WorldSeatHeight; } set { WPFMAToolDefaults.WorldSeatHeight = value; } }
        private static string status;
        private static bool statusIsError;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Seat maker", WPFMAUdonBridge.Available ? "make models sittable" : "needs UdonSharp", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Turn models into seats.", "Turns chair, bench and sofa models into seats players can click to sit on - many at once."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            if (!WPFMAUdonBridge.Available || WPFMAWorldTypes.Find(Station) == null)
            {
                WPFMAUdonBridge.NeedsUdonSharp();
                return;
            }

            var selected = Selection.gameObjects.Where(g => !EditorUtility.IsPersistent(g)).ToArray();
            EditorGUILayout.LabelField(selected.Length == 0 ? "Select the seat models in the Hierarchy." : selected.Length + " model(s) selected.",
                WPFMAToolSection.Hint(selected.Length == 0 ? WPFMAToolSection.FaintText : WPFMAToolSection.AccentBlue));

            seatHeight = EditorGUILayout.Slider("Seat height (m)", seatHeight, 0.1f, 1.2f);
            flip = EditorGUILayout.ToggleLeft(new GUIContent("Players face the other way", "If they sit backwards."), flip);

            using (new EditorGUI.DisabledScope(selected.Length == 0))
            {
                if (GUILayout.Button("Make " + selected.Length + " seat(s)", GUILayout.Height(26f)))
                {
                    var chosen = selected;
                    EditorApplication.delayCall += () => WPFMAChangeLog.Run("Seat maker", "Make " + chosen.Length + " seat(s)", null, true, () => { Make(chosen); return status; });
                }
            }

            EditorGUILayout.LabelField(new GUIContent("Nudge 'Seat Position' if needed.", "Each gets a 'Seat Position' child you can nudge if the player sits in the wrong spot."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

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

        private static void Make(GameObject[] seats)
        {
            var stationType = WPFMAWorldTypes.Find(Station);
            Undo.SetCurrentGroupName("Make seats");
            int group = Undo.GetCurrentGroup();
            int made = 0;
            string problem = null;

            foreach (var seat in seats)
            {
                if (seat == null || seat.GetComponent(stationType) != null)
                    continue;

                var renderers = seat.GetComponentsInChildren<Renderer>();
                var bounds = renderers.Length > 0 ? renderers[0].bounds : new Bounds(seat.transform.position, Vector3.one * 0.5f);
                foreach (var r in renderers.Skip(1))
                    bounds.Encapsulate(r.bounds);

                if (seat.GetComponent<Collider>() == null)
                {
                    var box = Undo.AddComponent<BoxCollider>(seat);
                    box.isTrigger = true;
                }

                var facing = Quaternion.LookRotation(Flatten(seat.transform.forward) * (flip ? -1f : 1f), Vector3.up);

                var enter = new GameObject("Seat Position");
                Undo.RegisterCreatedObjectUndo(enter, "Make seats");
                enter.transform.SetParent(seat.transform, true);
                enter.transform.position = new Vector3(bounds.center.x, bounds.min.y + seatHeight, bounds.center.z);
                enter.transform.rotation = facing;

                var exit = new GameObject("Seat Exit");
                Undo.RegisterCreatedObjectUndo(exit, "Make seats");
                exit.transform.SetParent(seat.transform, true);
                exit.transform.position = new Vector3(bounds.center.x, bounds.min.y, bounds.center.z) + facing * Vector3.forward * (bounds.extents.magnitude + 0.3f);
                exit.transform.rotation = facing;

                var station = Undo.AddComponent(seat, stationType);
                var serialized = new SerializedObject(station);
                var enterProperty = serialized.FindProperty("stationEnterPlayerLocation");
                var exitProperty = serialized.FindProperty("stationExitPlayerLocation");
                if (enterProperty != null)
                    enterProperty.objectReferenceValue = enter.transform;
                if (exitProperty != null)
                    exitProperty.objectReferenceValue = exit.transform;
                serialized.ApplyModifiedProperties();

                var proxy = WPFMAUdonBridge.Add(seat, Script, out problem);
                if (proxy == null)
                    break;

                WPFMAUdonBridge.Set(proxy, "station", station);
                WPFMAUdonBridge.Commit(proxy, "Sit");
                made++;
            }

            Undo.CollapseUndoOperations(group);
            status = problem ?? "Made " + made + " seat(s).";
            statusIsError = problem != null;
        }

        private static Vector3 Flatten(Vector3 direction)
        {
            direction.y = 0f;
            return direction.sqrMagnitude > 0.001f ? direction.normalized : Vector3.forward;
        }
    }

    internal static class WPFMAVideoScreenSection
    {
        private const string PrefKey = "WPFMA.Tools.VideoScreenExpanded";

        private static bool streams { get { return WPFMAToolDefaults.WorldVideoStreams; } set { WPFMAToolDefaults.WorldVideoStreams = value; } }
        private static float width { get { return WPFMAToolDefaults.WorldVideoWidth; } set { WPFMAToolDefaults.WorldVideoWidth = value; } }
        private static float range { get { return WPFMAToolDefaults.WorldVideoRange; } set { WPFMAToolDefaults.WorldVideoRange = value; } }
        private static string status;

        internal static void Draw(GUIStyle sectionStyle)
        {
            int count = WPFMAWorldTypes.Objects(WPFMAWorldTypes.UnityVideo).Count + WPFMAWorldTypes.Objects(WPFMAWorldTypes.AVProVideo).Count;
            WPFMAToolSection.Draw(sectionStyle, "Video screen helper", WPFMAWorldTypes.WorldSdkInstalled ? count + " video player(s)" : "needs the world SDK", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Place a synced video player.", "Places VRChat's synced video player facing you, sized to the screen width you want, with the sound " + "reaching as far as you set."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

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

            streams = GUILayout.Toolbar(streams ? 1 : 0, new[] { "Videos (Unity player)", "Videos + livestreams (AVPro)" }) == 1;
            width = EditorGUILayout.Slider("Screen width (m)", width, 1f, 30f);
            range = EditorGUILayout.Slider("Sound reaches (m)", range, 5f, 200f);

            int count = WPFMAWorldTypes.Objects(WPFMAWorldTypes.UnityVideo).Count + WPFMAWorldTypes.Objects(WPFMAWorldTypes.AVProVideo).Count;
            if (count >= 2)
                EditorGUILayout.LabelField("This scene already has " + count + " video players. VRChat recommends at most two per room.",
                    WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));

            if (GUILayout.Button("Place the video player", GUILayout.Height(26f)))
                EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Video screen helper", "Place a video player", null, true, () => Place());

            var selected = Selection.activeGameObject;
            bool isVideo = selected != null && (selected.GetComponentInChildren(WPFMAWorldTypes.Find(WPFMAWorldTypes.UnityVideo) ?? typeof(Light)) != null ||
                                                selected.GetComponentInChildren(WPFMAWorldTypes.Find(WPFMAWorldTypes.AVProVideo) ?? typeof(Light)) != null);
            using (new EditorGUI.DisabledScope(!isVideo))
                if (GUILayout.Button("Apply width and sound range to the selected player", EditorStyles.miniButton))
                    EditorApplication.delayCall += () => status = WPFMAChangeLog.Run("Video screen helper", "Resize the video player", null, true, () => Fit(Selection.activeGameObject));

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

        private static string Place()
        {
            string path = WPFMAWorldTypes.SdkPrefab(streams ? "UdonSyncPlayer (AVPro).prefab" : "UdonSyncPlayer (Unity).prefab");
            if (path == null)
                return "The video player prefab is not in this SDK version.";

            var instance = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<GameObject>(path));
            Undo.RegisterCreatedObjectUndo(instance, "Place video player");
            instance.transform.position = WPFMAWorldTypes.PlacementPoint() + Vector3.up * 1.5f;

            var view = SceneView.lastActiveSceneView;
            if (view != null)
            {
                var toCamera = view.camera.transform.position - instance.transform.position;
                toCamera.y = 0f;
                if (toCamera.sqrMagnitude > 0.001f)
                    instance.transform.rotation = Quaternion.LookRotation(-toCamera.normalized, Vector3.up);
            }

            Fit(instance);
            Selection.activeGameObject = instance;
            return "Placed the " + (streams ? "AVPro" : "Unity") + " video player. If the screen faces away, turn it 180 degrees.";
        }

        private static string Fit(GameObject player)
        {
            if (player == null)
                return "Select the video player.";

            var renderers = player.GetComponentsInChildren<Renderer>();
            if (renderers.Length > 0)
            {
                var bounds = renderers.OrderByDescending(r => r.bounds.size.x * r.bounds.size.y + r.bounds.size.z * r.bounds.size.y).First().bounds;
                float current = Mathf.Max(bounds.size.x, bounds.size.z);
                if (current > 0.01f)
                {
                    Undo.RecordObject(player.transform, "Size video player");
                    player.transform.localScale *= width / current;
                }
            }

            foreach (var audio in player.GetComponentsInChildren<AudioSource>(true))
            {
                Undo.RecordObject(audio, "Video sound range");
                audio.maxDistance = range;
                audio.minDistance = Mathf.Min(range * 0.15f, 5f);
                audio.spatialBlend = 1f;
                audio.rolloffMode = AudioRolloffMode.Linear;
            }

            return "Screen about " + width.ToString("0.#") + " m wide, sound reaching " + range.ToString("0") + " m.";
        }
    }
}
#endif
