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

namespace WPFMA
{
    internal static class WPFMAUdonBridge
    {
        internal const string ToggleScript = "WPFMA.Udon.WPFMAToggle";
        internal const string AudioZoneScript = "WPFMA.Udon.WPFMAAudioZone";

        internal static bool Available
        {
            get
            {
                return WPFMAWorldTypes.Find("UdonSharp.UdonSharpBehaviour") != null &&
                       WPFMAWorldTypes.Find("UdonSharpEditor.UdonSharpUndo") != null;
            }
        }

        internal static Component Add(GameObject target, string scriptName, out string problem)
        {
            problem = null;
            var scriptType = WPFMAWorldTypes.Find(scriptName);
            if (!Available || scriptType == null)
            {
                problem = "UdonSharp is not available. It comes with the VRChat world SDK - install that first, then let Unity finish compiling.";
                return null;
            }

            if (!EnsureProgram(scriptType, out problem))
                return null;

            var undo = WPFMAWorldTypes.Find("UdonSharpEditor.UdonSharpUndo");
            var add = undo.GetMethod("AddComponent", BindingFlags.Public | BindingFlags.Static, null,
                new[] { typeof(GameObject), typeof(Type) }, null);
            if (add == null)
            {
                problem = "This UdonSharp version has no AddComponent - add the " + scriptType.Name + " script by hand.";
                return null;
            }

            try
            {
                return (Component)add.Invoke(null, new object[] { target, scriptType });
            }
            catch (TargetInvocationException e)
            {
                problem = "UdonSharp could not add the script: " + (e.InnerException != null ? e.InnerException.Message : e.Message);
                return null;
            }
        }

        internal static void Set(Component proxy, string field, object value)
        {
            var info = proxy.GetType().GetField(field, BindingFlags.Public | BindingFlags.Instance);
            if (info != null)
                info.SetValue(proxy, value);
        }

        internal static void Commit(Component proxy, string interactText)
        {
            var util = WPFMAWorldTypes.Find("UdonSharpEditor.UdonSharpEditorUtility");
            var behaviourType = WPFMAWorldTypes.Find("UdonSharp.UdonSharpBehaviour");
            if (util == null || behaviourType == null)
                return;

            var copy = util.GetMethod("CopyProxyToUdon", BindingFlags.Public | BindingFlags.Static, null, new[] { behaviourType }, null);
            if (copy != null)
                copy.Invoke(null, new object[] { proxy });

            if (string.IsNullOrEmpty(interactText))
                return;

            var backing = util.GetMethod("GetBackingUdonBehaviour", BindingFlags.Public | BindingFlags.Static, null, new[] { behaviourType }, null);
            var udon = backing != null ? backing.Invoke(null, new object[] { proxy }) as Component : null;
            if (udon == null)
                return;

            var serialized = new SerializedObject(udon);
            var text = serialized.FindProperty("interactText");
            if (text != null)
            {
                text.stringValue = interactText;
                serialized.ApplyModifiedProperties();
            }
        }

        private static bool EnsureProgram(Type scriptType, out string problem)
        {
            problem = null;
            var programType = WPFMAWorldTypes.Find("UdonSharp.UdonSharpProgramAsset");
            var sourceField = programType != null ? programType.GetField("sourceCsScript") : null;
            if (programType == null || sourceField == null)
            {
                problem = "UdonSharp program assets are not available.";
                return false;
            }

            MonoScript script = null;
            foreach (var guid in AssetDatabase.FindAssets(scriptType.Name + " t:MonoScript"))
            {
                var candidate = AssetDatabase.LoadAssetAtPath<MonoScript>(AssetDatabase.GUIDToAssetPath(guid));
                if (candidate != null && candidate.GetClass() == scriptType)
                {
                    script = candidate;
                    break;
                }
            }

            if (script == null)
            {
                problem = "Could not find the " + scriptType.Name + " script file.";
                return false;
            }

            foreach (var guid in AssetDatabase.FindAssets("t:UdonSharpProgramAsset"))
            {
                var existing = AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(guid));
                if (existing != null && programType.IsInstanceOfType(existing) && (UnityEngine.Object)sourceField.GetValue(existing) == script)
                    return true;
            }

            var program = ScriptableObject.CreateInstance(programType);
            sourceField.SetValue(program, script);
            string path = AssetDatabase.GenerateUniqueAssetPath(Path.ChangeExtension(AssetDatabase.GetAssetPath(script), ".asset"));
            AssetDatabase.CreateAsset(program, path);
            AssetDatabase.SaveAssets();

            var compile = programType.GetMethod("CompileAllCsPrograms", BindingFlags.Public | BindingFlags.Static);
            if (compile != null)
                compile.Invoke(null, new object[] { true, true });

            return true;
        }

        internal static void NeedsUdonSharp()
        {
            EditorGUILayout.LabelField(new GUIContent("Needs UdonSharp (world SDK).", "This needs UdonSharp, which comes with the VRChat world SDK. In a world project it works here."), WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
        }
    }

    internal static class WPFMAToggleMakerSection
    {
        private const string PrefKey = "WPFMA.Tools.ToggleMakerExpanded";

        private static GameObject button;
        private static bool synced { get { return WPFMAToolDefaults.WorldToggleSynced; } set { WPFMAToolDefaults.WorldToggleSynced = value; } }
        private static bool startOff { get { return WPFMAToolDefaults.WorldToggleStartsOff; } set { WPFMAToolDefaults.WorldToggleStartsOff = value; } }
        private static string label = "Toggle";
        private static string status;
        private static bool statusIsError;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Toggle & button maker",
                WPFMAUdonBridge.Available ? Targets().Length + " selected" : "needs UdonSharp", PrefKey, Body);
        }

        private static GameObject[] Targets()
        {
            return Selection.gameObjects.Where(g => !EditorUtility.IsPersistent(g) && g != button).ToArray();
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("A button that toggles objects.", "Select what should turn on and off - a mirror, lights, props - and make a button for it. Players click " + "the button in VRChat to switch them."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

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

            var targets = Targets();
            EditorGUILayout.LabelField(targets.Length == 0
                    ? "Select the objects to switch in the Hierarchy."
                    : "Switches: " + string.Join(", ", targets.Take(5).Select(t => t.name).ToArray()) + (targets.Length > 5 ? "..." : string.Empty),
                WPFMAToolSection.Hint(targets.Length == 0 ? WPFMAToolSection.FaintText : WPFMAToolSection.AccentBlue));

            button = (GameObject)EditorGUILayout.ObjectField(new GUIContent("Use as the button", "Leave empty to make a new button cube."),
                button, typeof(GameObject), true);
            if (button != null && EditorUtility.IsPersistent(button))
                button = null;

            label = EditorGUILayout.TextField("Hover text", label);
            synced = EditorGUILayout.ToggleLeft("Everyone sees it change (synced)", synced);
            EditorGUILayout.LabelField(synced
                    ? "One click switches it for the whole instance, and late joiners see the current state."
                    : "Each player switches it just for themselves - best for mirrors.",
                WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            startOff = EditorGUILayout.ToggleLeft("Start switched off", startOff);

            using (new EditorGUI.DisabledScope(targets.Length == 0))
            {
                if (GUILayout.Button("Make the toggle", GUILayout.Height(26f)))
                {
                    var chosen = targets;
                    EditorApplication.delayCall += () => WPFMAChangeLog.Run("Toggle maker", "Make a toggle for " + chosen.Length + " object(s)", null, true, () => { Make(chosen); return status; });
                }
            }

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

        private static void Make(GameObject[] targets)
        {
            Undo.SetCurrentGroupName("Make toggle");
            int group = Undo.GetCurrentGroup();

            var host = button;
            if (host == null)
            {
                host = GameObject.CreatePrimitive(PrimitiveType.Cube);
                host.name = "Toggle - " + targets[0].name;
                host.transform.position = WPFMAWorldTypes.PlacementPoint() + Vector3.up * 1f;
                host.transform.localScale = Vector3.one * 0.2f;
                Undo.RegisterCreatedObjectUndo(host, "Make toggle");
            }
            else if (host.GetComponent<Collider>() == null)
            {
                Undo.AddComponent<BoxCollider>(host);
            }

            string problem;
            var proxy = WPFMAUdonBridge.Add(host, WPFMAUdonBridge.ToggleScript, out problem);
            if (proxy == null)
            {
                status = problem;
                statusIsError = true;
                return;
            }

            WPFMAUdonBridge.Set(proxy, "targets", targets);
            WPFMAUdonBridge.Set(proxy, "synced", synced);
            WPFMAUdonBridge.Commit(proxy, label);

            if (startOff)
            {
                foreach (var target in targets)
                {
                    Undo.RecordObject(target, "Make toggle");
                    target.SetActive(false);
                }
            }

            Undo.CollapseUndoOperations(group);
            Selection.activeGameObject = host;
            status = "Made a " + (synced ? "synced" : "local") + " toggle on '" + host.name + "' for " + targets.Length + " object(s).";
            statusIsError = false;
        }
    }

    internal static class WPFMAAudioZoneSection
    {
        private const string PrefKey = "WPFMA.Tools.AudioZoneExpanded";

        private static float fade { get { return WPFMAToolDefaults.WorldAudioFade; } set { WPFMAToolDefaults.WorldAudioFade = value; } }
        private static Vector3 size = new Vector3(10f, 4f, 10f);
        private static string status;
        private static bool statusIsError;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Audio zone maker", WPFMAUdonBridge.Available ? "fades music by area" : "needs UdonSharp", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Music that plays inside an area.", "Music or ambience that only plays while you are inside an area, fading in and out at the edges. Each " + "player hears it based on where they are."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

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

            var sources = Selection.gameObjects.Where(g => !EditorUtility.IsPersistent(g))
                .SelectMany(g => g.GetComponentsInChildren<AudioSource>(true)).Distinct().ToArray();

            EditorGUILayout.LabelField(sources.Length == 0
                    ? "Select the objects with the Audio Sources to fade."
                    : "Fades " + sources.Length + " audio source(s).",
                WPFMAToolSection.Hint(sources.Length == 0 ? WPFMAToolSection.FaintText : WPFMAToolSection.AccentBlue));

            size = EditorGUILayout.Vector3Field("Zone size (m)", size);
            fade = EditorGUILayout.Slider("Fade time (s)", fade, 0.1f, 6f);

            using (new EditorGUI.DisabledScope(sources.Length == 0))
            {
                if (GUILayout.Button("Make the audio zone", GUILayout.Height(26f)))
                {
                    var chosen = sources;
                    EditorApplication.delayCall += () => WPFMAChangeLog.Run("Audio zone maker", "Make an audio zone", null, true, () => { Make(chosen); return status; });
                }
            }

            EditorGUILayout.LabelField(new GUIContent("Move and stretch the box.", "The zone is a box where the Scene view is looking - move and stretch it to fit the room."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

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

        private static void Make(AudioSource[] sources)
        {
            Undo.SetCurrentGroupName("Make audio zone");
            int group = Undo.GetCurrentGroup();

            var zone = new GameObject("Audio Zone");
            Undo.RegisterCreatedObjectUndo(zone, "Make audio zone");
            zone.transform.position = WPFMAWorldTypes.PlacementPoint() + Vector3.up * size.y * 0.5f;
            var box = zone.AddComponent<BoxCollider>();
            box.isTrigger = true;
            box.size = size;

            string problem;
            var proxy = WPFMAUdonBridge.Add(zone, WPFMAUdonBridge.AudioZoneScript, out problem);
            if (proxy == null)
            {
                Undo.CollapseUndoOperations(group);
                status = problem;
                statusIsError = true;
                return;
            }

            foreach (var source in sources)
            {
                Undo.RecordObject(source, "Make audio zone");
                source.loop = true;
                source.playOnAwake = true;
            }

            WPFMAUdonBridge.Set(proxy, "sources", sources);
            WPFMAUdonBridge.Set(proxy, "fadeSeconds", fade);
            WPFMAUdonBridge.Commit(proxy, null);

            Undo.CollapseUndoOperations(group);
            Selection.activeGameObject = zone;
            status = "Made an audio zone for " + sources.Length + " source(s). They loop and fade over " + fade.ToString("0.#") + " s.";
            statusIsError = false;
        }
    }

    internal static class WPFMAPickupMakerSection
    {
        private const string PrefKey = "WPFMA.Tools.PickupMakerExpanded";

        private static bool syncedPickup { get { return WPFMAToolDefaults.WorldPickupSynced; } set { WPFMAToolDefaults.WorldPickupSynced = value; } }
        private static bool gravity { get { return WPFMAToolDefaults.WorldPickupGravity; } set { WPFMAToolDefaults.WorldPickupGravity = value; } }
        private static bool staysPut { get { return WPFMAToolDefaults.WorldPickupStaysPut; } set { WPFMAToolDefaults.WorldPickupStaysPut = value; } }
        private static string status;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Pickup maker", WPFMAWorldTypes.WorldSdkInstalled ? "make things grabbable" : "needs the world SDK", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Make objects grabbable.", "Turns the selected objects into things players can pick up: a collider, a Rigidbody, VRC Pickup and, " + "if you want, Object Sync so everyone sees it move."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

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

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

            syncedPickup = EditorGUILayout.ToggleLeft("Everyone sees it move (Object Sync)", syncedPickup);
            gravity = EditorGUILayout.ToggleLeft("Falls when dropped (gravity)", gravity);
            staysPut = EditorGUILayout.ToggleLeft("Floats where it is let go (kinematic)", staysPut);

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

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

        private static string Make(GameObject[] objects)
        {
            var pickupType = WPFMAWorldTypes.Find(WPFMAWorldTypes.Pickup);
            var syncType = WPFMAWorldTypes.Find("VRC.SDK3.Components.VRCObjectSync");
            int pickupLayer = LayerMask.NameToLayer("Pickup");

            Undo.SetCurrentGroupName("Make pickups");
            int group = Undo.GetCurrentGroup();

            foreach (var go in objects)
            {
                if (go == null)
                    continue;

                Undo.RecordObject(go, "Make pickups");
                GameObjectUtility.SetStaticEditorFlags(go, 0);
                if (pickupLayer >= 0)
                    go.layer = pickupLayer;

                var collider = go.GetComponent<Collider>();
                if (collider == null)
                {
                    collider = Undo.AddComponent<BoxCollider>(go);
                }
                else if (collider is MeshCollider mesh && !mesh.convex)
                {
                    Undo.RecordObject(mesh, "Make pickups");
                    mesh.convex = true;
                }

                var body = go.GetComponent<Rigidbody>();
                if (body == null)
                    body = Undo.AddComponent<Rigidbody>(go);
                Undo.RecordObject(body, "Make pickups");
                body.useGravity = gravity;
                body.isKinematic = staysPut;

                if (pickupType != null && go.GetComponent(pickupType) == null)
                    Undo.AddComponent(go, pickupType);

                if (syncedPickup && syncType != null && go.GetComponent(syncType) == null)
                    Undo.AddComponent(go, syncType);
            }

            Undo.CollapseUndoOperations(group);
            return "Made " + objects.Length + " pickup(s)" + (pickupLayer >= 0 ? " on the Pickup layer" : string.Empty) + ".";
        }
    }
}
#endif
