// 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.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace WPFMA.Team
{
    internal enum LinkEventKind
    {
        Up,
        PeerResumed,
        PeerHold,
        Lost,
        Bye,
        Reconnecting
    }

    internal sealed class LinkEvent
    {
        public LinkEventKind Kind;
        public string Text;
    }

    internal sealed class LinkInbound
    {
        public byte[] Json;
        public byte[] Blob;
    }

    /// <summary>
    /// The connection once two editors have found each other. Runs on its own thread so keep-alives continue while
    /// Unity is busy importing, and delivers messages of any size reliably and in order. Each side has an "epoch"
    /// number per editor domain; when one side reloads scripts it comes back with a new epoch, both reset the
    /// stream, and messages the other side had not had acknowledged are sent again.
    /// </summary>
    internal sealed class TeamLink
    {
        // 1200 bytes keeps every packet under the 1280-byte limit of VPNs such as Tailscale.
        private const int FragmentSize = 1200;
        private const int MinWindow = 64;
        private const int MaxWindow = 6144;
        private const double SilenceLimit = 12.0;
        private const double HoldLimit = 240.0;
        private const double GiveUpAfter = 30.0;
        private const double ResumeLimit = 120.0;
        // Long enough for a teammate whose Unity crashed to open it again and rejoin.
        private const double ReconnectLimit = 600.0;

        private sealed class OutMessage
        {
            public byte[] Data;
            public long Size;
            public int Offset;
            public uint LastSeq;
        }

        private sealed class Flight
        {
            public byte[] Packet;
            public double FirstSent;
            public double SentAt;
        }

        internal readonly ConcurrentQueue<LinkInbound> Inbox = new ConcurrentQueue<LinkInbound>();
        internal readonly ConcurrentQueue<LinkEvent> Events = new ConcurrentQueue<LinkEvent>();

        private readonly Socket socket;
        private readonly Stopwatch clock = Stopwatch.StartNew();
        private readonly ConcurrentQueue<KeyValuePair<byte[], byte[]>> toSend = new ConcurrentQueue<KeyValuePair<byte[], byte[]>>();
        private readonly ConcurrentQueue<byte[]> toSendLossy = new ConcurrentQueue<byte[]>();
        private readonly byte[] buffer = new byte[65536];
        private readonly object gate = new object();
        private int localEpoch;
        private readonly string code;
        private readonly TeamMessage helloTemplate;
        private byte[] helloPacket;
        private byte[] helloAckPacket;
        private double resumeLimit = ResumeLimit;

        private readonly List<OutMessage> unacked = new List<OutMessage>();
        private readonly Dictionary<uint, Flight> flights = new Dictionary<uint, Flight>();
        private readonly Dictionary<uint, byte[]> early = new Dictionary<uint, byte[]>();
        private MemoryStream assembling = new MemoryStream();

        private Thread thread;
        private volatile bool running;
        private IPEndPoint remote;
        private int remoteEpoch;
        private volatile string key;
        private bool resuming;
        private double resumeStarted;
        private double lastHeard;
        private double holdUntil;
        private uint nextSeq = 1;
        private uint oldestSeq = 1;
        private uint ackedThrough;
        private uint expected = 1;
        private int fragmentCursor;
        private long backlog;
        private volatile int rttMs = -1;
        private double srtt = 0.2;

        // Adaptive window: grows while the window is full and little is lost, shrinks when loss suggests the
        // connection (usually the sender's upload) is overloaded. Occasional random loss alone doesn't shrink it.
        private double window = 256;
        private int periodSent;
        private int periodLost;
        private double periodStart;
        private double lastResendScan;
        private double minRtt = 10;
        private double minRttAt;
        private double recentRtt = -1;

        // Epochs the other editor has moved past: a delayed hello from one of them must not rewind the link.
        private readonly HashSet<int> retiredEpochs = new HashSet<int>();

        // With several teammates on one port, a TeamMux reads the socket and hands each link its own packets.
        private readonly TeamMux mux;
        private readonly AutoResetEvent wake = new AutoResetEvent(false);

        /// <summary>The other editor's id (from its hello). Hellos from other editors are not for this link.</summary>
        internal readonly string PeerId;

        internal TeamLink(Socket socket, IPEndPoint remote, int localEpoch, int remoteEpoch, string code, string key,
            TeamMessage hello, bool resuming)
            : this(socket, null, null, remote, localEpoch, remoteEpoch, code, key, hello, resuming)
        {
        }

        internal TeamLink(Socket socket, TeamMux mux, string peerId, IPEndPoint remote, int localEpoch, int remoteEpoch, string code,
            string key, TeamMessage hello, bool resuming)
        {
            this.mux = mux;
            PeerId = string.IsNullOrEmpty(peerId) ? null : peerId;
            this.socket = socket;
            this.remote = remote;
            this.localEpoch = localEpoch;
            this.remoteEpoch = remoteEpoch;
            this.code = code;
            this.key = key ?? string.Empty;
            helloTemplate = hello;
            BuildHellos();
            this.resuming = resuming;
            resumeStarted = Now;
            lastHeard = Now;
        }

        private void BuildHellos()
        {
            helloTemplate.n = localEpoch;
            helloPacket = TeamPacket.Build(PacketType.Hello, 0, helloTemplate);
            helloAckPacket = TeamPacket.Build(PacketType.HelloAck, 0, helloTemplate);
        }

        /// <summary>
        /// The other editor went quiet: keep everything not yet delivered, start again with a new epoch and keep
        /// knocking on its last address. Both sides do this, which also reopens the holes in each router.
        /// </summary>
        private void BeginReconnect(double now)
        {
            int next = 0;
            var random = new Random();
            while (next == 0 || next == localEpoch)
                next = random.Next(1, int.MaxValue);
            localEpoch = next;
            BuildHellos();
            remoteEpoch = 0;
            resuming = true;
            resumeStarted = now;
            resumeLimit = ReconnectLimit;
            holdUntil = 0;
            ResetStream();
            Post(LinkEventKind.Reconnecting, null);
        }

        internal IPEndPoint Remote
        {
            get { lock (gate) return remote; }
        }

        internal string Key
        {
            get { return key; }
            set { key = value ?? string.Empty; }
        }

        internal int RemoteEpoch
        {
            get { lock (gate) return remoteEpoch; }
        }

        internal bool Resuming
        {
            get { lock (gate) return resuming; }
        }

        internal bool PeerOnHold
        {
            get { lock (gate) return holdUntil > Now; }
        }

        internal int PingMs
        {
            get { return rttMs; }
        }

        /// <summary>Bytes waiting to be delivered (queued plus not yet acknowledged).</summary>
        internal long Backlog
        {
            get { return Interlocked.Read(ref backlog); }
        }

        private double Now
        {
            get { return clock.Elapsed.TotalSeconds; }
        }

        internal bool Running
        {
            get { return running; }
        }

        /// <summary>A packet for this link, read from the shared socket by the TeamMux.</summary>
        internal void Feed(PacketType type, uint seq, byte[] body, IPEndPoint from)
        {
            if (!running)
                return;
            lock (gate)
                Handle(type, seq, body, from);
            wake.Set();
        }

        internal void Start()
        {
            running = true;
            if (mux != null)
                mux.Add(this);
            thread = new Thread(Run) { IsBackground = true, Name = "WPFMA Team link" };
            thread.Start();
        }

        internal void Stop()
        {
            running = false;
            if (mux != null)
                mux.Remove(this);
            wake.Set();
            if (thread != null && thread.IsAlive && thread != Thread.CurrentThread)
                thread.Join(1000);
            thread = null;
        }

        internal void Send(byte[] json, byte[] blob)
        {
            Interlocked.Add(ref backlog, json.Length + (blob != null ? blob.Length : 0));
            toSend.Enqueue(new KeyValuePair<byte[], byte[]>(json, blob));
            wake.Set();
        }

        internal void SendLossy(byte[] json)
        {
            if (toSendLossy.Count < 64)
                toSendLossy.Enqueue(json);
        }

        /// <summary>Sends a control packet straight away from the calling thread (used for goodbye and hold).</summary>
        internal void SendControl(PacketType type, string text)
        {
            var target = Remote;
            if (target == null)
                return;
            var packet = TeamPacket.BuildRaw(type, 0, Encoding.UTF8.GetBytes(text ?? string.Empty));
            for (int i = 0; i < 3; i++)
                SendTo(packet, target);
        }

        private void Run()
        {
            double lastKeep = -10;
            double lastHello = -10;

            while (running)
            {
                try
                {
                    if (mux != null)
                        wake.WaitOne(4);
                    else
                        socket.Poll(4000, SelectMode.SelectRead);
                }
                catch (Exception)
                {
                    if (!running)
                        return;
                }

                try
                {
                    if (mux == null)
                        ReceiveAll();

                    double now = Now;
                    bool waiting;
                    lock (gate)
                        waiting = resuming;

                    if (waiting)
                    {
                        if (now - lastHello > 0.3)
                        {
                            lastHello = now;
                            SendTo(helloPacket, Remote);
                        }
                        if (now - resumeStarted > resumeLimit)
                        {
                            Post(LinkEventKind.Lost, "could not reconnect after the reload");
                            running = false;
                        }
                        continue;
                    }

                    lock (gate)
                    {
                        PumpOutgoing(now);
                        if (!Resend(now))
                            BeginReconnect(now);
                    }

                    if (now - lastKeep > 1.0)
                    {
                        lastKeep = now;
                        var body = new byte[16];
                        WriteEpochs(body);
                        BitConverter.GetBytes(now).CopyTo(body, 8);
                        SendTo(TeamPacket.BuildRaw(PacketType.KeepAlive, 0, body), Remote);
                    }

                    lock (gate)
                    {
                        double limit = holdUntil > now ? (holdUntil - now) + SilenceLimit : SilenceLimit;
                        if (now - lastHeard > limit)
                            BeginReconnect(now);
                    }
                }
                catch (ObjectDisposedException)
                {
                    return;
                }
                catch (Exception e)
                {
                    UnityEngine.Debug.LogWarning("[WPFMA Team] Link error: " + e.Message);
                }
            }
        }

        private void WriteEpochs(byte[] body)
        {
            BitConverter.GetBytes(localEpoch).CopyTo(body, 0);
            BitConverter.GetBytes(remoteEpoch).CopyTo(body, 4);
        }

        private bool EpochsMatch(byte[] body)
        {
            return body.Length >= 8 && BitConverter.ToInt32(body, 0) == remoteEpoch && BitConverter.ToInt32(body, 4) == localEpoch;
        }

        private void PumpOutgoing(double now)
        {
            KeyValuePair<byte[], byte[]> item;
            while (toSend.TryDequeue(out item))
                unacked.Add(new OutMessage { Data = Encode(item.Key, item.Value), Size = item.Key.Length + (item.Value != null ? item.Value.Length : 0) });

            AdjustWindow(now);
            while (flights.Count < (int)window && fragmentCursor < unacked.Count)
            {
                var message = unacked[fragmentCursor];
                if (message.Offset >= message.Data.Length)
                {
                    fragmentCursor++;
                    continue;
                }

                int length = Math.Min(FragmentSize, message.Data.Length - message.Offset);
                bool last = message.Offset + length == message.Data.Length;
                uint seq = nextSeq++;

                var body = new byte[9 + length];
                WriteEpochs(body);
                body[8] = (byte)(last ? 1 : 0);
                System.Buffer.BlockCopy(message.Data, message.Offset, body, 9, length);
                message.Offset += length;
                if (last)
                {
                    message.LastSeq = seq;
                    fragmentCursor++;
                }

                var packet = TeamPacket.BuildRaw(PacketType.Reliable, seq, body);
                flights[seq] = new Flight { Packet = packet, FirstSent = now, SentAt = now };
                periodSent++;
                SendTo(packet, remote);
            }

            byte[] lossy;
            while (toSendLossy.TryDequeue(out lossy))
            {
                var body = new byte[8 + lossy.Length];
                WriteEpochs(body);
                System.Buffer.BlockCopy(lossy, 0, body, 8, lossy.Length);
                SendTo(TeamPacket.BuildRaw(PacketType.Data, 0, body), remote);
            }
        }

        private void AdjustWindow(double now)
        {
            double period = Math.Max(0.05, srtt * 2.0);
            if (now - periodStart < period)
                return;
            if (periodSent >= 32)
            {
                double loss = periodLost / (double)periodSent;
                // Packets taking clearly longer than the quickest seen means a queue is filling somewhere.
                bool queueing = recentRtt > 0 && recentRtt > minRtt * 2.0 + 0.02;
                if (loss > 0.08)
                    window = Math.Max(MinWindow, window * 0.7);
                else if (queueing)
                    window = Math.Max(MinWindow, window * 0.9);
                else if (flights.Count >= window * 0.9)
                    window = Math.Min(MaxWindow, window * (loss < 0.03 ? 1.4 : 1.12));
            }
            periodStart = now;
            periodSent = 0;
            periodLost = 0;
        }

        internal int WindowSize
        {
            get { return (int)window; }
        }

        private bool Resend(double now)
        {
            if (now - lastResendScan < 0.01)
                return true;
            lastResendScan = now;
            double timeout = Math.Min(2.0, Math.Max(0.2, srtt * 1.5 + 0.05));
            int budget = 512;

            foreach (var pair in flights)
            {
                var flight = pair.Value;
                if (now - flight.SentAt < timeout)
                    continue;
                if (now - flight.FirstSent > GiveUpAfter && holdUntil < now)
                    return false;
                flight.SentAt = now;
                periodLost++;
                SendTo(flight.Packet, remote);
                if (--budget <= 0)
                    break;
            }

            return true;
        }

        private void Acknowledge(uint seq, uint cumulative)
        {
            Flight acked;
            if (flights.TryGetValue(seq, out acked) && acked.SentAt == acked.FirstSent)
            {
                double now = Now;
                double sample = now - acked.FirstSent;
                recentRtt = recentRtt < 0 ? sample : recentRtt * 0.9 + sample * 0.1;
                if (sample < minRtt || now - minRttAt > 10.0)
                {
                    minRtt = sample;
                    minRttAt = now;
                }
            }
            flights.Remove(seq);
            if (cumulative > ackedThrough)
                ackedThrough = cumulative;
            while (oldestSeq <= ackedThrough)
            {
                flights.Remove(oldestSeq);
                oldestSeq++;
            }

            while (unacked.Count > 0)
            {
                var first = unacked[0];
                if (first.Offset < first.Data.Length || first.LastSeq == 0 || first.LastSeq > ackedThrough)
                    break;
                unacked.RemoveAt(0);
                if (fragmentCursor > 0)
                    fragmentCursor--;
                Interlocked.Add(ref backlog, -first.Size);
            }
        }

        /// <summary>The other editor restarted its side: start the stream over and resend anything not yet confirmed.</summary>
        private void ResetStream()
        {
            flights.Clear();
            nextSeq = 1;
            oldestSeq = 1;
            ackedThrough = 0;
            fragmentCursor = 0;
            foreach (var message in unacked)
            {
                message.Offset = 0;
                message.LastSeq = 0;
            }

            expected = 1;
            early.Clear();
            assembling = new MemoryStream();
        }

        private void ReceiveAll()
        {
            while (running)
            {
                int length;
                EndPoint sender = new IPEndPoint(IPAddress.Any, 0);
                try
                {
                    if (socket.Available <= 0)
                        return;
                    length = socket.ReceiveFrom(buffer, ref sender);
                }
                catch (SocketException)
                {
                    return;
                }

                PacketType type;
                uint seq;
                byte[] body;
                if (!TeamPacket.Parse(buffer, length, out type, out seq, out body))
                    continue;

                var from = (IPEndPoint)sender;
                lock (gate)
                    Handle(type, seq, body, from);
            }
        }

        private void Handle(PacketType type, uint seq, byte[] body, IPEndPoint from)
        {
            double now = Now;

            if (type == PacketType.Hello || type == PacketType.HelloAck)
            {
                HandleHello(type, body, from, now);
                return;
            }

            if (resuming || !from.Equals(remote))
                return;

            switch (type)
            {
                case PacketType.Bye:
                    Post(LinkEventKind.Bye, Encoding.UTF8.GetString(body));
                    running = false;
                    return;

                case PacketType.Hold:
                {
                    // "600|closed Unity" waits 600 seconds; plain text waits the default.
                    string text = Encoding.UTF8.GetString(body);
                    double seconds = HoldLimit;
                    int bar = text.IndexOf('|');
                    if (bar > 0 && double.TryParse(text.Substring(0, bar), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out seconds))
                        text = text.Substring(bar + 1);
                    else
                        seconds = HoldLimit;
                    lastHeard = now;
                    if (holdUntil < now)
                        Post(LinkEventKind.PeerHold, text);
                    holdUntil = now + seconds;
                    return;
                }
            }

            if (!EpochsMatch(body))
                return;

            lastHeard = now;

            switch (type)
            {
                case PacketType.KeepAlive:
                    if (body.Length >= 16)
                    {
                        var pong = new byte[16];
                        WriteEpochs(pong);
                        System.Buffer.BlockCopy(body, 8, pong, 8, 8);
                        SendTo(TeamPacket.BuildRaw(PacketType.Pong, 0, pong), remote);
                    }
                    return;

                case PacketType.Pong:
                    if (body.Length >= 16)
                    {
                        double rtt = Math.Max(0, now - BitConverter.ToDouble(body, 8));
                        srtt = srtt * 0.8 + rtt * 0.2;
                        rttMs = (int)(rtt * 1000.0);
                    }
                    return;

                case PacketType.Ack:
                    if (body.Length >= 12)
                        Acknowledge(seq, BitConverter.ToUInt32(body, 8));
                    return;

                case PacketType.Data:
                    Inbox.Enqueue(new LinkInbound { Json = Slice(body, 8) });
                    return;

                case PacketType.Reliable:
                    ReceiveReliable(seq, body);
                    return;
            }
        }

        private void HandleHello(PacketType type, byte[] body, IPEndPoint from, double now)
        {
            var message = TeamPacket.Json(body);
            if (message == null || TeamPacket.NormalizeCode(message.code) != code || message.n == 0)
                return;
            // Another teammate's hello (same session key) is not for this link.
            if (PeerId != null && !string.IsNullOrEmpty(message.g) && message.g != PeerId)
                return;
            // The other side came back from a reload with a different WPFMA-SDK: stop rather than half-work.
            if (message.mt != TeamPacket.Protocol && (string.IsNullOrEmpty(key) || message.key == key))
            {
                Post(LinkEventKind.Lost, "a different WPFMA-SDK " + (message.m == TeamPacket.SdkVersion ? "build" : "version") +
                                         " (" + (string.IsNullOrEmpty(message.m) ? "older" : message.m) + ")");
                running = false;
                return;
            }

            string expectedKey = key;
            bool keyOk = !string.IsNullOrEmpty(expectedKey) && message.key == expectedKey;
            if (!keyOk && !from.Equals(remote))
                return;

            if (type == PacketType.Hello)
                SendTo(helloAckPacket, from);

            if (message.n == remoteEpoch && !resuming)
            {
                lastHeard = now;
                return;
            }
            if (retiredEpochs.Contains(message.n))
                return;

            bool wasResuming = resuming;
            if (remoteEpoch != 0)
                retiredEpochs.Add(remoteEpoch);
            remote = from;
            remoteEpoch = message.n;
            resuming = false;
            holdUntil = 0;
            lastHeard = now;
            ResetStream();
            Post(wasResuming ? LinkEventKind.Up : LinkEventKind.PeerResumed, message.name);
        }

        private void ReceiveReliable(uint seq, byte[] body)
        {
            if (body.Length < 9)
                return;

            var ack = new byte[12];
            WriteEpochs(ack);
            if (seq >= expected && seq < expected + MaxWindow * 3 && !early.ContainsKey(seq))
                early[seq] = body;

            while (early.TryGetValue(expected, out var next))
            {
                early.Remove(expected);
                expected++;
                assembling.Write(next, 9, next.Length - 9);
                if ((next[8] & 1) != 0)
                {
                    Deliver(assembling.ToArray());
                    assembling = new MemoryStream();
                }
            }

            BitConverter.GetBytes(expected - 1).CopyTo(ack, 8);
            SendTo(TeamPacket.BuildRaw(PacketType.Ack, seq, ack), remote);
        }

        private static byte[] Encode(byte[] json, byte[] blob)
        {
            int blobLength = blob != null ? blob.Length : 0;
            var raw = new byte[4 + json.Length + blobLength];
            BitConverter.GetBytes(json.Length).CopyTo(raw, 0);
            System.Buffer.BlockCopy(json, 0, raw, 4, json.Length);
            if (blobLength > 0)
                System.Buffer.BlockCopy(blob, 0, raw, 4 + json.Length, blobLength);

            if (raw.Length > 300)
            {
                var packed = TeamPacket.Compress(raw);
                if (packed.Length < raw.Length - 64)
                    return Prefix(1, packed);
            }

            return Prefix(0, raw);
        }

        private void Deliver(byte[] data)
        {
            try
            {
                if (data.Length < 1)
                    return;
                byte[] raw = data[0] == 1 ? TeamPacket.Decompress(Slice(data, 1)) : Slice(data, 1);
                int jsonLength = BitConverter.ToInt32(raw, 0);
                if (jsonLength < 0 || jsonLength > raw.Length - 4)
                    return;

                var json = new byte[jsonLength];
                System.Buffer.BlockCopy(raw, 4, json, 0, jsonLength);
                byte[] blob = null;
                int blobLength = raw.Length - 4 - jsonLength;
                if (blobLength > 0)
                {
                    blob = new byte[blobLength];
                    System.Buffer.BlockCopy(raw, 4 + jsonLength, blob, 0, blobLength);
                }

                Inbox.Enqueue(new LinkInbound { Json = json, Blob = blob });
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogWarning("[WPFMA Team] Dropped a damaged message: " + e.Message);
            }
        }

        private static byte[] Prefix(byte flag, byte[] data)
        {
            var result = new byte[data.Length + 1];
            result[0] = flag;
            System.Buffer.BlockCopy(data, 0, result, 1, data.Length);
            return result;
        }

        private static byte[] Slice(byte[] data, int start)
        {
            var result = new byte[Math.Max(0, data.Length - start)];
            System.Buffer.BlockCopy(data, start, result, 0, result.Length);
            return result;
        }

        private void Post(LinkEventKind kind, string text)
        {
            Events.Enqueue(new LinkEvent { Kind = kind, Text = text });
        }

        private void SendTo(byte[] packet, IPEndPoint target)
        {
            if (target == null)
                return;
            try
            {
                socket.SendTo(packet, target);
            }
            catch (SocketException)
            {
            }
            catch (ObjectDisposedException)
            {
            }
        }
    }

    internal sealed class MuxPacket
    {
        public byte[] Data;
        public int Length;
        public IPEndPoint From;
    }

    /// <summary>
    /// Reads the one UDP port every teammate talks to and hands each packet to that teammate's link. Hellos are
    /// matched by the sender's editor id (their address can change when they reconnect); everything else by
    /// address. Packets no link wants (someone joining, internet address lookups) go to the session.
    /// </summary>
    internal sealed class TeamMux
    {
        private readonly Socket socket;
        private readonly byte[] buffer = new byte[65536];
        private readonly object gate = new object();
        private volatile TeamLink[] links = new TeamLink[0];
        private Thread thread;
        private volatile bool running;

        internal readonly ConcurrentQueue<MuxPacket> Unrouted = new ConcurrentQueue<MuxPacket>();

        internal TeamMux(Socket socket)
        {
            this.socket = socket;
        }

        internal void Add(TeamLink link)
        {
            lock (gate)
            {
                var list = new List<TeamLink>(links);
                if (!list.Contains(link))
                    list.Add(link);
                links = list.ToArray();
            }
        }

        internal void Remove(TeamLink link)
        {
            lock (gate)
            {
                var list = new List<TeamLink>(links);
                list.Remove(link);
                links = list.ToArray();
            }
        }

        internal void Start()
        {
            running = true;
            thread = new Thread(Run) { IsBackground = true, Name = "WPFMA Team port" };
            thread.Start();
        }

        internal void Stop()
        {
            running = false;
            if (thread != null && thread.IsAlive && thread != Thread.CurrentThread)
                thread.Join(1000);
            thread = null;
        }

        private void Run()
        {
            while (running)
            {
                try
                {
                    socket.Poll(4000, SelectMode.SelectRead);
                }
                catch (Exception)
                {
                    if (!running)
                        return;
                }

                while (running)
                {
                    int length;
                    EndPoint sender = new IPEndPoint(IPAddress.Any, 0);
                    try
                    {
                        if (socket.Available <= 0)
                            break;
                        length = socket.ReceiveFrom(buffer, ref sender);
                    }
                    catch (SocketException)
                    {
                        break;
                    }
                    catch (ObjectDisposedException)
                    {
                        return;
                    }

                    try
                    {
                        Route(length, (IPEndPoint)sender);
                    }
                    catch (Exception e)
                    {
                        UnityEngine.Debug.LogWarning("[WPFMA Team] Port error: " + e.Message);
                    }
                }
            }
        }

        private void Route(int length, IPEndPoint from)
        {
            PacketType type;
            uint seq;
            byte[] body;
            if (TeamStun.IsStun(buffer, length) || !TeamPacket.Parse(buffer, length, out type, out seq, out body))
            {
                ToSession(length, from);
                return;
            }

            var current = links;
            if (type == PacketType.Hello || type == PacketType.HelloAck)
            {
                var message = TeamPacket.Json(body);
                string id = message != null ? message.g : null;
                foreach (var link in current)
                {
                    if (!string.IsNullOrEmpty(id) && link.PeerId == id)
                    {
                        link.Feed(type, seq, body, from);
                        return;
                    }
                }
                // Not one of ours yet: someone joining.
                ToSession(length, from);
                return;
            }

            foreach (var link in current)
            {
                if (from.Equals(link.Remote))
                {
                    link.Feed(type, seq, body, from);
                    return;
                }
            }
        }

        private void ToSession(int length, IPEndPoint from)
        {
            if (Unrouted.Count > 512)
                return;
            var copy = new byte[length];
            System.Buffer.BlockCopy(buffer, 0, copy, 0, length);
            Unrouted.Enqueue(new MuxPacket { Data = copy, Length = length, From = from });
        }
    }
}
#endif
