// 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.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

namespace WPFMA
{
    [InitializeOnLoad]
    internal static class WPFMADiscordPresence
    {
        private const string ApplicationId = "1548800388533329920";
        private const string DefaultLargeImageKey = "discordpresence";
        private const double UpdateInterval = 15d;
        private const string RpcEnabledPrefKey = "WPFMA.DiscordRpc.Enabled";
        private const string RpcShowPanelPrefKey = "WPFMA.DiscordRpc.ShowPanelState";
        private const string RpcShowStatePrefKey = "WPFMA.DiscordRpc.ShowState";
        private const string RpcImageKeyPrefKey = "WPFMA.DiscordRpc.ImageKey";

        private static DiscordIpcClient client;
        private static double nextUpdateTime;
        private static long sessionStart;
        private static string panelState = "Importer";
        private static string busyState;
        private static double busyUntil;
        private static string lastDetails;
        private static string lastState;
        private static string connectionStatus = "Not connected yet.";
        private static bool connected;
        private static bool rpcEnabled = true;
        private static bool showPanelState = true;
        private static bool showState = true;

        static WPFMADiscordPresence()
        {
            rpcEnabled = EditorPrefs.GetBool(RpcEnabledPrefKey, true);
            showPanelState = EditorPrefs.GetBool(RpcShowPanelPrefKey, true);
            showState = EditorPrefs.GetBool(RpcShowStatePrefKey, true);
            sessionStart = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            EditorApplication.update += Update;
            EditorSceneManager.sceneOpened += OnSceneChanged;
            EditorSceneManager.activeSceneChangedInEditMode += OnActiveSceneChanged;
            AssemblyReloadEvents.beforeAssemblyReload += Disconnect;
        }

        private static void Update()
        {
            if (!string.IsNullOrEmpty(busyState) && EditorApplication.timeSinceStartup >= busyUntil)
                busyState = null;

            if (EditorApplication.timeSinceStartup < nextUpdateTime)
                return;

            nextUpdateTime = EditorApplication.timeSinceStartup + UpdateInterval;
            Publish();
        }

        internal static void SetPanelState(string panel)
        {
            string normalized = string.IsNullOrWhiteSpace(panel) ? "Importer" : panel.Trim();
            if (string.Equals(panelState, normalized, StringComparison.Ordinal))
                return;

            panelState = normalized;
            Publish(true);
        }

        internal static void SetBusyState(string state, double holdSeconds = 20d)
        {
            if (string.IsNullOrWhiteSpace(state))
                return;

            busyState = state.Trim();
            busyUntil = EditorApplication.timeSinceStartup + Math.Max(holdSeconds, UpdateInterval);
            Publish(true);
        }

        internal static void ClearBusyState()
        {
            if (string.IsNullOrEmpty(busyState))
                return;

            busyState = null;
            busyUntil = 0d;
            Publish(true);
        }

        internal static string LargeImageKey
        {
            get
            {
                string key = EditorPrefs.GetString(RpcImageKeyPrefKey, DefaultLargeImageKey);
                return string.IsNullOrWhiteSpace(key) ? DefaultLargeImageKey : key.Trim();
            }
            set
            {
                EditorPrefs.SetString(RpcImageKeyPrefKey, (value ?? string.Empty).Trim());
                Publish(true);
            }
        }

        internal static string ConnectionStatus => connectionStatus;

        internal static bool Connected => connected;

        internal static void Reconnect()
        {
            client?.Dispose();
            client = null;
            connected = false;
            connectionStatus = "Reconnecting...";
            lastDetails = null;
            lastState = null;
            Publish(true);
        }

        internal static bool RpcEnabled => rpcEnabled;
        internal static bool ShowPanelState => showPanelState;
        internal static bool ShowState => showState;

        internal static void Configure(bool enabled, bool showPanel, bool showStatus)
        {
            bool changed = rpcEnabled != enabled || showPanelState != showPanel || showState != showStatus;

            rpcEnabled = enabled;
            showPanelState = showPanel;
            showState = showStatus;

            EditorPrefs.SetBool(RpcEnabledPrefKey, rpcEnabled);
            EditorPrefs.SetBool(RpcShowPanelPrefKey, showPanelState);
            EditorPrefs.SetBool(RpcShowStatePrefKey, showState);

            if (!changed)
                return;

            if (!rpcEnabled)
            {
                ClearActivity();
                return;
            }

            Publish(true);
        }

        private static void OnSceneChanged(UnityEngine.SceneManagement.Scene scene, OpenSceneMode mode) => Publish();
        private static void OnActiveSceneChanged(UnityEngine.SceneManagement.Scene previous, UnityEngine.SceneManagement.Scene current) => Publish();

        private static void Publish(bool force = false)
        {
            if (!rpcEnabled)
                return;

            var projectName = Application.productName;
            if (string.IsNullOrWhiteSpace(projectName))
                projectName = new DirectoryInfo(Application.dataPath).Parent?.Name ?? "Unity Project";
            var sceneName = EditorSceneManager.GetActiveScene().name;
            if (string.IsNullOrWhiteSpace(sceneName))
                sceneName = "No scene open";

            string details = showPanelState
                ? "Working in " + projectName + " (" + panelState + ")"
                : "Working in " + projectName;

            string state = string.Empty;
            if (showState)
                state = string.IsNullOrEmpty(busyState) ? "Scene: " + sceneName : busyState;

            if (!force && string.Equals(lastDetails, details, StringComparison.Ordinal) &&
                string.Equals(lastState, state, StringComparison.Ordinal))
                return;

            lastDetails = details;
            lastState = state;

            var activity = new ActivityPayload
            {
                cmd = "SET_ACTIVITY",
                args = new ActivityArgs
                {
                    pid = Process.GetCurrentProcess().Id,
                    activity = new Activity
                    {
                        details = details,
                        state = state,
                        timestamps = new Timestamps { start = sessionStart },
                        assets = new Assets
                        {
                            large_image = LargeImageKey,
                            large_text = "WPFMA-SDK"
                        },
                        instance = false
                    }
                },
                nonce = Guid.NewGuid().ToString()
            };

            try
            {
                if (client == null || !client.IsConnected)
                {
                    client?.Dispose();
                    client = DiscordIpcClient.Connect(ApplicationId);
                }

                client.SetActivity(activity);
                connected = true;
                connectionStatus = "Connected to Discord.";
            }
            catch (Exception e)
            {
                client?.Dispose();
                client = null;
                connected = false;
                connectionStatus = e.Message;
            }
        }

        private static void ClearActivity()
        {
            try
            {
                if (client == null || !client.IsConnected)
                {
                    client?.Dispose();
                    client = DiscordIpcClient.Connect(ApplicationId);
                }

                var clearActivity = new ActivityPayload
                {
                    cmd = "SET_ACTIVITY",
                    args = new ActivityArgs
                    {
                        pid = Process.GetCurrentProcess().Id,
                        activity = null
                    },
                    nonce = Guid.NewGuid().ToString()
                };

                client.SetActivity(clearActivity);
            }
            catch
            {
                client?.Dispose();
                client = null;
            }
        }

        private static void Disconnect()
        {
            EditorApplication.update -= Update;
            EditorSceneManager.sceneOpened -= OnSceneChanged;
            EditorSceneManager.activeSceneChangedInEditMode -= OnActiveSceneChanged;
            AssemblyReloadEvents.beforeAssemblyReload -= Disconnect;
            client?.Dispose();
            client = null;
        }

        private sealed class DiscordIpcClient : IDisposable
        {
            private Stream stream;
            private Socket socket;

            public bool IsConnected => stream != null && (socket == null || socket.Connected);

            private DiscordIpcClient(Stream stream, Socket socket)
            {
                this.stream = stream;
                this.socket = socket;
            }

            public static DiscordIpcClient Connect(string applicationId)
            {
                bool windows = Application.platform == RuntimePlatform.WindowsEditor;
                bool found = false;

                for (var index = 0; index < 10; index++)
                {
                    DiscordIpcClient client = windows ? OpenPipe(index) : OpenSocket(index);
                    if (client == null)
                        continue;

                    found = true;

                    try
                    {
                        client.Write(0, new HandshakePayload { v = 1, client_id = applicationId });

                        string reply;
                        int opcode;
                        if (client.TryRead(700, out opcode, out reply) && opcode == 2)
                            throw new IOException(DescribeClose(reply, applicationId));

                        return client;
                    }
                    catch (IOException)
                    {
                        client.Dispose();
                        throw;
                    }
                    catch (Exception)
                    {
                        client.Dispose();
                    }
                }

                throw new IOException(found
                    ? "Found Discord's socket but the handshake failed."
                    : windows
                        ? "Discord is not running, or it cannot be reached from this process. " +
                          "If Unity runs as administrator and Discord does not, Windows hides the pipe from it."
                        : "Discord is not running, or its socket is not visible to Unity. A Flatpak or Snap " +
                          "install keeps it inside the sandbox, where the editor cannot see it.");
            }

            private static DiscordIpcClient OpenPipe(int index)
            {
                var candidate = new NamedPipeClientStream(".", "discord-ipc-" + index,
                    PipeDirection.InOut, PipeOptions.Asynchronous);
                try
                {
                    candidate.Connect(250);
                    return new DiscordIpcClient(candidate, null);
                }
                catch (Exception)
                {
                    candidate.Dispose();
                    return null;
                }
            }

            private static DiscordIpcClient OpenSocket(int index)
            {
                foreach (var folder in SocketFolders())
                {
                    string path = Path.Combine(folder, "discord-ipc-" + index);
                    if (!File.Exists(path))
                        continue;

                    var candidate = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
                    try
                    {
                        candidate.Connect(new UnixDomainSocketEndPoint(path));
                        return new DiscordIpcClient(new NetworkStream(candidate, false), candidate);
                    }
                    catch (Exception)
                    {
                        candidate.Dispose();
                    }
                }

                return null;
            }

            private static IEnumerable<string> SocketFolders()
            {
                var roots = new List<string>();
                foreach (var variable in new[] { "XDG_RUNTIME_DIR", "TMPDIR", "TMP", "TEMP" })
                {
                    string value = Environment.GetEnvironmentVariable(variable);
                    if (!string.IsNullOrEmpty(value) && !roots.Contains(value))
                        roots.Add(value);
                }

                if (!roots.Contains("/tmp"))
                    roots.Add("/tmp");

                var folders = new List<string>();
                foreach (var root in roots)
                {
                    folders.Add(root);
                    folders.Add(Path.Combine(root, "app", "com.discordapp.Discord"));
                    folders.Add(Path.Combine(root, "app", "com.discordapp.DiscordCanary"));
                    folders.Add(Path.Combine(root, "snap.discord"));
                }

                return folders;
            }

            private static string DescribeClose(string json, string applicationId)
            {
                if (!string.IsNullOrEmpty(json) && json.IndexOf("4000", StringComparison.Ordinal) >= 0)
                    return "Discord rejected application id " + applicationId +
                           ". Check the ID on the app's OAuth2 page.";

                return "Discord closed the connection: " + (string.IsNullOrEmpty(json) ? "no reason given" : json);
            }

            public void SetActivity(ActivityPayload activity)
            {
                Write(1, activity);
            }

            private void Write<T>(int opcode, T payload)
            {
                var jsonString = JsonUtility.ToJson(payload);
                var json = Encoding.UTF8.GetBytes(jsonString);
                var header = new byte[8];
                BitConverter.GetBytes(opcode).CopyTo(header, 0);
                BitConverter.GetBytes(json.Length).CopyTo(header, 4);
                stream.Write(header, 0, header.Length);
                stream.Write(json, 0, json.Length);
                stream.Flush();
            }

            private bool TryRead(int timeoutMs, out int opcode, out string json)
            {
                opcode = 0;
                json = null;

                try
                {
                    var header = new byte[8];
                    var read = stream.ReadAsync(header, 0, header.Length);
                    if (!read.Wait(timeoutMs) || read.Result < header.Length)
                        return false;

                    opcode = BitConverter.ToInt32(header, 0);
                    int length = BitConverter.ToInt32(header, 4);
                    if (length <= 0 || length > 65536)
                        return true;

                    var body = new byte[length];
                    var bodyRead = stream.ReadAsync(body, 0, length);
                    if (!bodyRead.Wait(timeoutMs))
                        return true;

                    json = Encoding.UTF8.GetString(body, 0, bodyRead.Result);
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }

            public void Dispose()
            {
                if (stream != null)
                {
                    try
                    {
                        stream.Dispose();
                    }
                    catch (Exception)
                    {
                    }

                    stream = null;
                }

                if (socket != null)
                {
                    try
                    {
                        socket.Dispose();
                    }
                    catch (Exception)
                    {
                    }

                    socket = null;
                }
            }
        }

        [Serializable] private struct HandshakePayload { public int v; public string client_id; }
        [Serializable] private struct ActivityPayload { public string cmd; public ActivityArgs args; public string nonce; }
        [Serializable] private struct ActivityArgs { public int pid; public Activity activity; }
        [Serializable] private sealed class Activity { public string details; public string state; public Timestamps timestamps; public Assets assets; public bool instance; }
        [Serializable] private struct Timestamps { public long start; }
        [Serializable] private struct Assets { public string large_image; public string large_text; }
    }
}
#endif
