// 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.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using UnityEngine;

namespace WPFMA.Team
{
    internal enum PacketType : byte
    {
        Hello = 1,
        HelloAck = 2,
        Data = 3,
        Reliable = 4,
        Ack = 5,
        KeepAlive = 6,
        Bye = 7,
        Pong = 8,
        Hold = 10
    }

    [Serializable]
    internal sealed class TeamMessage
    {
        public string t;
        public float[] p;
        public float[] r;
        public bool o;
        public string m;
        public string s;
        public string[] paths;
        public string name;
        public string code;
        public string key;
        public string pwd;
        public string reason;
        public double ts;
        public string json;
        public string f;
        public string h;
        public string d;
        public string mt;
        public string[] a;
        public string[] b;
        public int n;
        public bool on;
        // Which editor a message is from (or about), so the host can pass teammates' messages on to each other.
        public string g;
        // Which teammate a message is for, when it has to go through the host (guest to guest).
        public string to;
        // The scene a scene edit belongs to, so an editor without that scene open (like a host passing it on) skips it.
        public string sc;
    }

    /// <summary>Many scene edits in one message: one packet, compressed together, instead of one per object.</summary>
    [Serializable]
    internal sealed class TeamBundle
    {
        public TeamMessage[] list;
    }

    internal static class TeamPacket
    {
        private const byte MagicA = (byte)'W';
        private const byte MagicB = (byte)'T';
        private const byte Version = 1;

        internal static byte[] Build(PacketType type, uint seq, TeamMessage message)
        {
            return BuildRaw(type, seq, message != null ? Encode(message) : new byte[0]);
        }

        internal static byte[] BuildRaw(PacketType type, uint seq, byte[] body)
        {
            var packet = new byte[8 + body.Length];
            packet[0] = MagicA;
            packet[1] = MagicB;
            packet[2] = Version;
            packet[3] = (byte)type;
            BitConverter.GetBytes(seq).CopyTo(packet, 4);
            body.CopyTo(packet, 8);
            return packet;
        }

        internal static bool Parse(byte[] data, int length, out PacketType type, out uint seq, out byte[] body)
        {
            type = 0;
            seq = 0;
            body = null;

            if (length < 8 || data[0] != MagicA || data[1] != MagicB || data[2] != Version)
                return false;

            type = (PacketType)data[3];
            seq = BitConverter.ToUInt32(data, 4);
            body = new byte[length - 8];
            System.Buffer.BlockCopy(data, 8, body, 0, body.Length);
            return true;
        }

        /// <summary>
        /// Bumped whenever two editors running different Team code could misunderstand each other. Both sides must
        /// match to connect; the SDK version is sent along only to make the message clear.
        /// </summary>
        internal const string Protocol = "wpfma-team-10";

        private static string sdkVersion;

        internal static string SdkVersion
        {
            get
            {
                if (sdkVersion != null)
                    return sdkVersion;
                sdkVersion = "?";
                try
                {
                    const string manifest = "Packages/com.wpfma.sdk/package.json";
                    if (File.Exists(manifest))
                    {
                        var match = Regex.Match(File.ReadAllText(manifest), "\"version\"\\s*:\\s*\"([^\"]+)\"");
                        if (match.Success)
                            sdkVersion = match.Groups[1].Value;
                    }
                }
                catch (Exception)
                {
                }
                return sdkVersion;
            }
        }

        internal static string NormalizeCode(string code)
        {
            return new string((code ?? string.Empty).ToUpperInvariant().Where(char.IsLetterOrDigit).ToArray());
        }

        internal static TeamMessage Json(byte[] body)
        {
            if (body == null || body.Length == 0)
                return null;
            try
            {
                return Filled(JsonUtility.FromJson<TeamMessage>(Encoding.UTF8.GetString(body)));
            }
            catch (Exception)
            {
                return null;
            }
        }

        // An empty field written out ("name":"", "a":[], "o":false, "n":0): left out of what's sent.
        private static readonly Regex EmptyField = new Regex("\"[A-Za-z_][A-Za-z0-9_]*\":(?:\"\"|\\[\\]|false|0|0\\.0)(?=[,}])", RegexOptions.Compiled);

        /// <summary>
        /// A message as sent: its JSON without the fields that are empty. Every message has 25 fields and most are
        /// empty, so this is often half the size. (Messages inside "json" are escaped, so they're never touched.)
        /// </summary>
        internal static byte[] Encode(TeamMessage message)
        {
            return Encoding.UTF8.GetBytes(EncodeText(message));
        }

        internal static string EncodeText(TeamMessage message)
        {
            string json = EmptyField.Replace(JsonUtility.ToJson(message), string.Empty);
            while (json.Contains(",,"))
                json = json.Replace(",,", ",");
            return json.Replace("{,", "{").Replace(",}", "}");
        }

        /// <summary>
        /// Fields that weren't sent are filled in empty, exactly as they used to arrive (Unity's JSON reader leaves a
        /// missing text or list as null, and some code expects "" or an empty list).
        /// </summary>
        internal static TeamMessage Filled(TeamMessage message)
        {
            if (message == null)
                return null;
            message.t = message.t ?? string.Empty;
            message.m = message.m ?? string.Empty;
            message.s = message.s ?? string.Empty;
            message.name = message.name ?? string.Empty;
            message.code = message.code ?? string.Empty;
            message.key = message.key ?? string.Empty;
            message.pwd = message.pwd ?? string.Empty;
            message.reason = message.reason ?? string.Empty;
            message.json = message.json ?? string.Empty;
            message.f = message.f ?? string.Empty;
            message.h = message.h ?? string.Empty;
            message.d = message.d ?? string.Empty;
            message.mt = message.mt ?? string.Empty;
            message.g = message.g ?? string.Empty;
            message.to = message.to ?? string.Empty;
            message.sc = message.sc ?? string.Empty;
            message.p = message.p ?? new float[0];
            message.r = message.r ?? new float[0];
            message.paths = message.paths ?? new string[0];
            message.a = message.a ?? new string[0];
            message.b = message.b ?? new string[0];
            return message;
        }

        internal static byte[] Compress(byte[] data)
        {
            using (var output = new MemoryStream())
            {
                using (var gzip = new System.IO.Compression.GZipStream(output, System.IO.Compression.CompressionLevel.Fastest))
                    gzip.Write(data, 0, data.Length);
                return output.ToArray();
            }
        }

        internal static byte[] Decompress(byte[] data)
        {
            using (var input = new MemoryStream(data))
            using (var gzip = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress))
            using (var output = new MemoryStream())
            {
                gzip.CopyTo(output);
                return output.ToArray();
            }
        }
    }

    internal static class TeamStun
    {
        internal static readonly string[] Servers =
        {
            "stun.l.google.com:19302",
            "stun1.l.google.com:19302",
            "stun.cloudflare.com:3478"
        };

        private const uint MagicCookie = 0x2112A442;

        internal static byte[] Request(out byte[] transaction)
        {
            transaction = new byte[12];
            new System.Random().NextBytes(transaction);

            var packet = new byte[20];
            packet[0] = 0x00;
            packet[1] = 0x01;
            packet[2] = 0x00;
            packet[3] = 0x00;
            packet[4] = 0x21;
            packet[5] = 0x12;
            packet[6] = 0xA4;
            packet[7] = 0x42;
            Buffer.BlockCopy(transaction, 0, packet, 8, 12);
            return packet;
        }

        internal static bool IsStun(byte[] data, int length)
        {
            return length >= 20 && data[0] == 0x01 && data[1] == 0x01 &&
                   data[4] == 0x21 && data[5] == 0x12 && data[6] == 0xA4 && data[7] == 0x42;
        }

        internal static IPEndPoint ParseResponse(byte[] data, int length, byte[] transaction)
        {
            if (!IsStun(data, length))
                return null;

            for (int i = 0; i < 12; i++)
                if (data[8 + i] != transaction[i])
                    return null;

            int offset = 20;
            IPEndPoint mapped = null;

            while (offset + 4 <= length)
            {
                int type = (data[offset] << 8) | data[offset + 1];
                int size = (data[offset + 2] << 8) | data[offset + 3];
                int value = offset + 4;
                if (value + size > length)
                    break;

                if ((type == 0x0020 || type == 0x0001) && size >= 8 && data[value + 1] == 0x01)
                {
                    int port = (data[value + 2] << 8) | data[value + 3];
                    var address = new byte[] { data[value + 4], data[value + 5], data[value + 6], data[value + 7] };

                    if (type == 0x0020)
                    {
                        port ^= (int)(MagicCookie >> 16);
                        address[0] ^= 0x21;
                        address[1] ^= 0x12;
                        address[2] ^= 0xA4;
                        address[3] ^= 0x42;
                        return new IPEndPoint(new IPAddress(address), port);
                    }

                    mapped = new IPEndPoint(new IPAddress(address), port);
                }

                offset = value + ((size + 3) & ~3);
            }

            return mapped;
        }
    }

    internal static class TeamUpnp
    {
        private const string MappingName = "WPFMA Team";

        internal sealed class Mapping
        {
            public string ControlUrl;
            public string ServiceType;
            public int Port;
        }

        internal static Mapping TryOpen(int port, string localIp)
        {
            try
            {
                var device = Discover();
                if (device == null)
                    return null;

                string body =
                    "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + port + "</NewExternalPort><NewProtocol>UDP</NewProtocol>" +
                    "<NewInternalPort>" + port + "</NewInternalPort><NewInternalClient>" + localIp + "</NewInternalClient>" +
                    "<NewEnabled>1</NewEnabled><NewPortMappingDescription>" + MappingName + "</NewPortMappingDescription>" +
                    "<NewLeaseDuration>7200</NewLeaseDuration>";

                if (!Soap(device.ControlUrl, device.ServiceType, "AddPortMapping", body))
                    return null;

                device.Port = port;
                return device;
            }
            catch (Exception)
            {
                return null;
            }
        }

        internal static void Close(Mapping mapping)
        {
            if (mapping == null)
                return;

            try
            {
                Soap(mapping.ControlUrl, mapping.ServiceType, "DeletePortMapping",
                    "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + mapping.Port + "</NewExternalPort><NewProtocol>UDP</NewProtocol>");
            }
            catch (Exception)
            {
            }
        }

        private static Mapping Discover()
        {
            string[] targets =
            {
                "urn:schemas-upnp-org:service:WANIPConnection:1",
                "urn:schemas-upnp-org:service:WANIPConnection:2",
                "urn:schemas-upnp-org:service:WANPPPConnection:1"
            };

            var locations = new HashSet<string>();
            using (var client = new UdpClient())
            {
                client.Client.ReceiveTimeout = 600;
                var group = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900);

                foreach (var target in targets)
                {
                    string search = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 1\r\nST: " + target + "\r\n\r\n";
                    var bytes = Encoding.ASCII.GetBytes(search);
                    client.Send(bytes, bytes.Length, group);
                }

                var until = DateTime.UtcNow.AddSeconds(2);
                while (DateTime.UtcNow < until)
                {
                    try
                    {
                        var remote = new IPEndPoint(IPAddress.Any, 0);
                        var reply = Encoding.ASCII.GetString(client.Receive(ref remote));
                        var match = Regex.Match(reply, @"^LOCATION:\s*(\S+)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                        if (match.Success)
                            locations.Add(match.Groups[1].Value.Trim());
                    }
                    catch (SocketException)
                    {
                        break;
                    }
                }
            }

            foreach (var location in locations)
            {
                try
                {
                    var request = (HttpWebRequest)WebRequest.Create(location);
                    request.Timeout = 2000;
                    string xml;
                    using (var response = request.GetResponse())
                    using (var reader = new StreamReader(response.GetResponseStream()))
                        xml = reader.ReadToEnd();

                    foreach (Match service in Regex.Matches(xml, @"<service>(.*?)</service>", RegexOptions.Singleline | RegexOptions.IgnoreCase))
                    {
                        string block = service.Groups[1].Value;
                        var type = Regex.Match(block, @"<serviceType>\s*(.*?)\s*</serviceType>", RegexOptions.IgnoreCase).Groups[1].Value;
                        if (!targets.Contains(type))
                            continue;

                        var control = Regex.Match(block, @"<controlURL>\s*(.*?)\s*</controlURL>", RegexOptions.IgnoreCase).Groups[1].Value;
                        if (string.IsNullOrEmpty(control))
                            continue;

                        return new Mapping { ControlUrl = new Uri(new Uri(location), control).ToString(), ServiceType = type };
                    }
                }
                catch (Exception)
                {
                }
            }

            return null;
        }

        private static bool Soap(string url, string serviceType, string action, string arguments)
        {
            string envelope =
                "<?xml version=\"1.0\"?><s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
                "s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><s:Body><u:" + action + " xmlns:u=\"" + serviceType + "\">" +
                arguments + "</u:" + action + "></s:Body></s:Envelope>";

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Timeout = 3000;
            request.ContentType = "text/xml; charset=\"utf-8\"";
            request.Headers.Add("SOAPACTION", "\"" + serviceType + "#" + action + "\"");
            var bytes = Encoding.UTF8.GetBytes(envelope);
            request.ContentLength = bytes.Length;
            using (var stream = request.GetRequestStream())
                stream.Write(bytes, 0, bytes.Length);

            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                    return response.StatusCode == HttpStatusCode.OK;
            }
            catch (WebException)
            {
                return false;
            }
        }
    }

    internal static class TeamHttp
    {
        internal static Task<string> Post(string path, Dictionary<string, string> fields)
        {
            string url = WPFMAArchive.BaseUrl.TrimEnd('/') + path;
            string body = string.Join("&", fields.Select(f => Uri.EscapeDataString(f.Key) + "=" + Uri.EscapeDataString(f.Value ?? string.Empty)).ToArray());

            return Task.Run(() =>
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Timeout = 8000;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "WPFMA-SDK Team (Unity editor tool)";
                var bytes = Encoding.UTF8.GetBytes(body);
                request.ContentLength = bytes.Length;
                using (var stream = request.GetRequestStream())
                    stream.Write(bytes, 0, bytes.Length);

                try
                {
                    using (var response = request.GetResponse())
                    using (var reader = new StreamReader(response.GetResponseStream()))
                        return reader.ReadToEnd();
                }
                catch (WebException e)
                {
                    if (e.Response == null)
                        throw;
                    using (var reader = new StreamReader(e.Response.GetResponseStream()))
                        return reader.ReadToEnd();
                }
            });
        }
    }

    internal static class TeamAddress
    {
        internal static string LocalIp()
        {
            try
            {
                using (var probe = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                {
                    probe.Connect("8.8.8.8", 65530);
                    var local = probe.LocalEndPoint as IPEndPoint;
                    return local != null ? local.Address.ToString() : null;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        internal static IPEndPoint Parse(string text)
        {
            if (string.IsNullOrEmpty(text))
                return null;

            text = text.Trim();
            int colon = text.LastIndexOf(':');
            if (colon <= 0)
                return null;

            string host = text.Substring(0, colon).Trim('[', ']');
            int port;
            if (!int.TryParse(text.Substring(colon + 1), out port) || port < 1 || port > 65535)
                return null;

            IPAddress address;
            if (IPAddress.TryParse(host, out address))
                return address.AddressFamily == AddressFamily.InterNetwork ? new IPEndPoint(address, port) : null;

            try
            {
                var resolved = Dns.GetHostAddresses(host).FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
                return resolved != null ? new IPEndPoint(resolved, port) : null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>Home network, Tailscale/CGNAT or this PC: addresses that aren't someone's internet address.</summary>
        internal static bool IsPrivate(IPAddress address)
        {
            var b = address.GetAddressBytes();
            if (b.Length != 4)
                return true;
            return b[0] == 10 || b[0] == 127 || (b[0] == 172 && b[1] >= 16 && b[1] <= 31) || (b[0] == 192 && b[1] == 168) ||
                   (b[0] == 100 && b[1] >= 64 && b[1] <= 127) || (b[0] == 169 && b[1] == 254);
        }

        internal static string Format(IPEndPoint endPoint)
        {
            return endPoint == null ? string.Empty : endPoint.Address + ":" + endPoint.Port;
        }
    }
}
#endif
