// 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.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

namespace WPFMA.Team
{
    internal enum TeamState
    {
        Idle,
        Preparing,
        Waiting,
        Connecting,
        Connected,
        Reconnecting
    }

    internal sealed class TeamChatLine
    {
        public string Name;
        public string Text;
        public bool Mine;
        public bool System;
        public string Time;
        public Color Color;
    }

    internal sealed class TeamPing
    {
        public Vector3 Position;
        public string Name;
        public bool Mine;
        public double Time;
        public Color Color;
    }

    [Serializable]
    internal sealed class TeamReply
    {
        public bool ok;
        public string error;
        public string message;
        public string code;
        public string secret;
        public string seen_ip;
        public string host_name;
        public string host_public;
        public string host_local;
        public string host_seen_ip;
        public string peer_key;
        public bool waiting;
        public string guest_name;
        public string guest_public;
        public string guest_local;
        public string guest_seen_ip;
        public long guest_at;
    }

    [Serializable]
    internal sealed class TeamSaved
    {
        public string code;
        public bool host;
        public string key;
        public int port;
        public long savedAt;
        public string files;
        public bool waiting;
        public bool restart;
        public string address;
        public string secret;
        public string password;
        public string seenIp;
        // A guest taking over as host when Unity reloaded (see TeamSession.SuspendHandoff).
        public string takeoverSecret;
        public string takeoverKey;
        public long takeoverHandled;
        public string[] peerIds;
        public string[] peerNames;
        public string[] peerCodes;
        public string[] peerKeys;
        public string[] peerRemotes;
        public string[] peerScenes;
        public string[] chatNames;
        public string[] chatTexts;
        public string[] chatTimes;
        public bool[] chatMine;
        public bool[] chatSystem;
    }

    /// <summary>
    /// Someone else in the session. The host has a direct link to every guest; a guest has a link to the host only,
    /// and hears about the other guests through the host (their camera, selection, chat and edits are passed on).
    /// </summary>
    internal sealed class TeamPeer
    {
        internal string Id;
        internal string Name;
        internal string Code;
        internal string Key;
        internal Color Color;
        internal TeamLink Link;
        internal IPEndPoint Remote;
        internal bool Up;
        internal bool IsHost;

        internal string Scene;
        internal string ScenePath;
        // When they went into that scene (this editor's clock): whoever opens a scene later joins whoever is already there.
        internal double SceneSince;
        internal bool Playing;
        internal string Prefab;
        internal string Window;
        internal string Asset;
        internal bool HasCamera;
        // How they look in your Scene view (see TeamLook). Older SDKs never send it, so they stay a ball.
        internal string LookShape = "Ball";
        internal Color? LookColor;
        internal string LookHat = "None";
        internal string LookFace = "None";
        internal Vector3 CameraPosition;
        internal Quaternion CameraRotation = Quaternion.identity;
        internal string[] Selection = new string[0];
        internal string[] SelectionIds = new string[0];
        internal double UploadAt = -1000;
        internal string UploadKind;

        // What they still have on its way (files, scene changes...), empty when they're ready to upload.
        internal string Pending;

        // This editor was restarted: once this teammate's link is up, tell them so they start the scene over.
        internal bool RestartPending;

        // Host: the last selection/scene/activity this guest shared, replayed to a guest who joins later.
        internal readonly Dictionary<string, TeamMessage> LastPresence = new Dictionary<string, TeamMessage>();

        internal bool Linked
        {
            get { return Link != null; }
        }

        internal int PingMs
        {
            get { return Link != null ? Link.PingMs : -1; }
        }

        internal bool Busy
        {
            get { return Link != null && Link.PeerOnHold; }
        }

        internal long Backlog
        {
            get { return Link != null ? Link.Backlog : 0; }
        }
    }

    [InitializeOnLoad]
    internal static partial class TeamSession
    {
        private const string NameKey = "WPFMA.Team.Name";
        private const string PortKey = "WPFMA.Team.Port";
        private const string IdKey = "WPFMA.Team.Id.";
        private const string ResumeKey = "WPFMA.Team.Resume";
        private const string RejoinKey = "WPFMA.Team.Rejoin.";
        private const double RejoinMinutes = 10.0;
        private const int DefaultPort = 47320;
        private const double PrepareTimeout = 4.0;
        private const double PunchTimeout = 15.0;

        /// <summary>How many people can join the host: 4 people in all at most (the user's choice).</summary>
        internal const int MaxGuests = 3;

        internal static readonly Color[] Palette =
        {
            new Color(1f, 0.58f, 0.18f),
            new Color(0.36f, 0.85f, 0.45f),
            new Color(0.75f, 0.52f, 1f),
            new Color(1f, 0.45f, 0.7f)
        };

        internal static Color LocalColor => WPFMATheme.Shift(new Color(0.49f, 0.71f, 0.87f));

        internal static TeamState State { get; private set; }
        internal static bool IsHost { get; private set; }
        internal static string Code { get; private set; }
        internal static string Status { get; private set; }
        internal static string Error { get; private set; }
        internal static readonly List<string> Steps = new List<string>();
        internal static int BoundPort { get; private set; }
        internal static readonly List<TeamChatLine> Chat = new List<TeamChatLine>();
        internal static readonly List<TeamPing> Pings = new List<TeamPing>();
        internal static bool Following;
        internal static string FollowId;
        internal static int Unread;

        /// <summary>Everyone else in the session (on a guest this includes the other guests, reached through the host).</summary>
        internal static readonly List<TeamPeer> Peers = new List<TeamPeer>();

        /// <summary>
        /// The teammate whose message, link-up or restart is being handled right now (null otherwise). Modules use it
        /// to answer only that teammate (Reply) and to name them in messages.
        /// </summary>
        internal static TeamPeer Sender { get; private set; }

        private static double lastActivitySent;
        private static string lastActivity;

        /// <summary>Raised whenever anything shown in the Team tab changes.</summary>
        internal static event Action Changed;

        /// <summary>A teammate's link is up (Sender). True when this is a reconnection after a reload.</summary>
        internal static event Action<bool> LinkUp;

        /// <summary>A message for one of the sync features (files, scene, project); Sender is who it came from.</summary>
        internal static event Action<TeamMessage, byte[]> Received;

        /// <summary>The session is about to end (still connected, scenes still shared).</summary>
        internal static event Action Ending;

        /// <summary>The session ended for good.</summary>
        internal static event Action Ended;

        /// <summary>One teammate (Sender) left; the session goes on with the others.</summary>
        internal static event Action PeerLeft;

        /// <summary>Unity is about to reload scripts; save anything that must survive it.</summary>
        internal static event Action Suspending;

        /// <summary>A teammate (Sender) was restarted (Unity closed and opened), so it has no scene state any more.</summary>
        internal static event Action PeerRestarted;

        /// <summary>This editor rejoined after Unity was restarted.</summary>
        internal static event Action Restarted;

        private sealed class JoinAttempt
        {
            public List<IPEndPoint> Candidates = new List<IPEndPoint>();
            public List<IPEndPoint> Predicted = new List<IPEndPoint>();
            public double Started;
            public double LastPunch = -10;
            public double LastPredicted = -10;
            public string Name;
            public string Code;
            public string Key;
        }

        private static Socket socket;
        private static TeamMux mux;
        private static JoinAttempt joining;

        // The address used with "Join by address", so a script reload while connecting can start it again.
        private static string joinAddress;

        // The join the host is (or was last) connecting to, so a retry from the guest is noticed.
        private static long handledGuestAt;
        private static string secret;
        private static string peerKey;
        private static string password;
        private static string localIp;
        private static string seenIp;
        private static int localEpoch;
        private static double lastFullNote = -100;

        private static double prepareStarted;
        private static IPEndPoint[] stunServers;
        private static Task<IPEndPoint[]> stunLookup;
        private static IPEndPoint stunResult;
        private static byte[] stunTransaction;
        private static int stunIndex;
        private static double stunSentAt;
        private static bool stunFinished;
        private static Task<TeamUpnp.Mapping> upnpTask;
        private static TeamUpnp.Mapping upnp;

        private static Task<string> request;
        private static string requestKind;
        private static double lastPoll;
        private static double lastCameraSent;
        private static Vector3 lastCameraPosition;
        private static Quaternion lastCameraRotation;
        private static bool suspending;
        private static bool rejoined;
        private static bool renewing;

        static TeamSession()
        {
            EditorApplication.update += Update;
            EditorApplication.update += RunScheduled;
            Selection.selectionChanged += OnSelectionChanged;
            EditorSceneManager.activeSceneChangedInEditMode += (a, b) => SendScene();
            EditorSceneManager.sceneSaved += scene => SendScene();
            EditorApplication.playModeStateChanged += change => SendScene();
            AssemblyReloadEvents.beforeAssemblyReload += Suspend;
            EditorApplication.quitting += OnQuitting;
            EditorApplication.delayCall += TryResume;
            UnityEditor.SceneManagement.PrefabStage.prefabStageOpened += stage => SendScene();
            UnityEditor.SceneManagement.PrefabStage.prefabStageClosing += stage => EditorApplication.delayCall += SendScene;
        }

        internal static string DisplayName
        {
            get
            {
                string name = EditorPrefs.GetString(NameKey, string.Empty).Trim();
                return string.IsNullOrEmpty(name) ? "Creator" : name;
            }
            set { EditorPrefs.SetString(NameKey, (value ?? string.Empty).Trim()); }
        }

        internal static int Port
        {
            get { return Mathf.Clamp(EditorPrefs.GetInt(PortKey, DefaultPort), 1024, 65535); }
            set { EditorPrefs.SetInt(PortKey, Mathf.Clamp(value, 1024, 65535)); }
        }

        /// <summary>This editor's id in sessions (the same across reloads and restarts, different per project).</summary>
        internal static string LocalId
        {
            get
            {
                string key = IdKey + ProjectKey;
                string id = EditorPrefs.GetString(key, string.Empty);
                if (string.IsNullOrEmpty(id))
                {
                    id = Guid.NewGuid().ToString("N").Substring(0, 16);
                    EditorPrefs.SetString(key, id);
                }
                return id;
            }
        }

        internal static double Now
        {
            get { return EditorApplication.timeSinceStartup; }
        }

        // ---- Who is here --------------------------------------------------------------------------------------------

        /// <summary>Teammates this editor has a direct link to (the guests on the host, the host on a guest).</summary>
        internal static IEnumerable<TeamPeer> Linked
        {
            get { return Peers.Where(p => p.Link != null); }
        }

        internal static int GuestCount
        {
            get { return IsHost ? Peers.Count(p => p.Link != null) : Peers.Count(p => !p.IsHost) + 1; }
        }

        internal static bool HasRoom
        {
            get { return IsHost && Peers.Count(p => p.Link != null) < MaxGuests; }
        }

        /// <summary>The host, seen from a guest (null on the host).</summary>
        internal static TeamPeer HostPeer
        {
            get { return IsHost ? null : Peers.FirstOrDefault(p => p.IsHost); }
        }

        /// <summary>The teammate a single-person message is about: who is being handled now, else the host (guest) or first guest.</summary>
        internal static TeamPeer Primary
        {
            get { return Sender ?? HostPeer ?? Peers.FirstOrDefault(p => p.Link != null) ?? Peers.FirstOrDefault(); }
        }

        internal static TeamPeer FindPeer(string id)
        {
            return string.IsNullOrEmpty(id) ? null : Peers.FirstOrDefault(p => p.Id == id);
        }

        internal static bool IsLinked
        {
            get { return State == TeamState.Connected && Peers.Any(p => p.Link != null && p.Up); }
        }

        /// <summary>The teammate(s) being talked about: the sender while handling a message, else everyone's names.</summary>
        internal static string RemoteName
        {
            get
            {
                if (Sender != null)
                    return Sender.Name;
                var host = HostPeer;
                if (host != null)
                    return host.Name;
                var names = Peers.Where(p => p.Link != null).Select(p => p.Name).Where(n => !string.IsNullOrEmpty(n)).ToList();
                if (names.Count == 0)
                    return null;
                return names.Count == 1 ? names[0] : string.Join(" & ", names.ToArray());
            }
        }

        internal static Color RemoteColor
        {
            get { return Primary != null ? Primary.Color : Palette[0]; }
        }

        internal static int PingMs
        {
            get { return Primary != null ? Primary.PingMs : -1; }
        }

        /// <summary>Bytes not yet delivered to anyone (all links together).</summary>
        internal static long Backlog
        {
            get { return Peers.Sum(p => p.Backlog); }
        }

        internal static bool PeerBusy
        {
            get { return Peers.Any(p => p.Busy); }
        }

        /// <summary>Everything any teammate has selected in the scene (by shared id).</summary>
        internal static string[] RemoteSelectionIds
        {
            get { return Peers.SelectMany(p => p.SelectionIds ?? new string[0]).Distinct().ToArray(); }
        }

        internal static string[] RemoteSelection
        {
            get { return Peers.SelectMany(p => p.Selection ?? new string[0]).Distinct().ToArray(); }
        }

        /// <summary>The newest upload start by any teammate.</summary>
        internal static double RemoteUploadAt
        {
            get { return Peers.Count == 0 ? -1000 : Peers.Max(p => p.UploadAt); }
        }

        internal static string RemoteScene
        {
            get { return Primary != null ? Primary.Scene : null; }
        }

        /// <summary>The teammate (if any) who has this asset selected.</summary>
        internal static TeamPeer WhoHasAsset(string path)
        {
            return string.IsNullOrEmpty(path) ? null : Peers.FirstOrDefault(p => p.Asset == path);
        }

        /// <summary>The teammate (if any) who has this scene object selected.</summary>
        internal static TeamPeer WhoSelected(string id)
        {
            return string.IsNullOrEmpty(id) ? null : Peers.FirstOrDefault(p => p.SelectionIds != null && p.SelectionIds.Contains(id));
        }

        private static TeamPeer AddPeer(string id, string name)
        {
            var peer = FindPeer(id);
            if (peer != null)
            {
                if (!string.IsNullOrEmpty(name))
                    peer.Name = name;
                return peer;
            }
            peer = new TeamPeer { Id = id, Name = string.IsNullOrEmpty(name) ? "Teammate" : name };
            var used = new HashSet<Color>(Peers.Select(p => p.Color));
            peer.Color = Palette.FirstOrDefault(c => !used.Contains(c));
            if (peer.Color == default(Color))
                peer.Color = Palette[Peers.Count % Palette.Length];
            Peers.Add(peer);
            return peer;
        }

        // ---- Starting and ending ------------------------------------------------------------------------------------

        /// <summary>
        /// A new session always starts clean: state a module kept from an earlier session (for example one whose
        /// reconnect failed after a reload) is cleared first.
        /// </summary>
        private static void ClearModules()
        {
            if (Ended == null)
                return;
            foreach (Action handler in Ended.GetInvocationList())
            {
                try
                {
                    handler();
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                }
            }
        }

        internal static void StartHost(string sessionPassword)
        {
            Reset();
            ClearModules();
            IsHost = true;
            password = sessionPassword ?? string.Empty;
            Prepare();
        }

        /// <summary>
        /// Hosts without reqid.io: for the same home network or Tailscale. Friends use "Join by address" with
        /// this PC's address, the port and the code shown.
        /// </summary>
        internal static void StartHostDirect(string sessionPassword)
        {
            Reset();
            ClearModules();
            IsHost = true;
            password = sessionPassword ?? string.Empty;
            if (!Bind(Port))
                return;

            localEpoch = NewEpoch();
            const string letters = "ABCDEFGHJKMNPQRSTVWXYZ23456789";
            var bytes = new byte[6];
            using (var rng = RandomNumberGenerator.Create())
                rng.GetBytes(bytes);
            Code = new string(bytes.Select(b => letters[b % letters.Length]).ToArray());
            localIp = TeamAddress.LocalIp();
            Step("Listening on " + (localIp ?? "this PC") + ":" + BoundPort + " (no website used)");
            State = TeamState.Waiting;
            Status = WaitingText();
            Raise();
        }

        internal static void Join(string code, string sessionPassword)
        {
            Reset();
            ClearModules();
            IsHost = false;
            Code = NormalizeCode(code);
            password = sessionPassword ?? string.Empty;
            Prepare();
        }

        internal static void JoinAddress(string address, string code, string sessionPassword)
        {
            Reset();
            ClearModules();
            IsHost = false;
            Code = NormalizeCode(code);
            password = sessionPassword ?? string.Empty;

            if (!Bind(Port))
                return;

            var target = TeamAddress.Parse(address);
            if (target == null)
            {
                Fail("That address is not an IP and port, like 100.64.1.2:" + DefaultPort + ".");
                return;
            }
            joinAddress = address;

            peerKey = string.Empty;
            BeginPunch(new List<IPEndPoint> { target }, null, Code, string.Empty);
            Step("Connecting straight to " + TeamAddress.Format(target));
        }

        /// <summary>keepRoom: the host is handing its invite to a guest, so it must stay open on reqid.io.</summary>
        internal static void Leave(string reason = null, bool quiet = false, bool keepRoom = false)
        {
            if (State == TeamState.Connected && Ending != null)
            {
                foreach (Action handler in Ending.GetInvocationList())
                {
                    try
                    {
                        handler();
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);
                    }
                }
            }
            foreach (var peer in Linked.ToList())
                peer.Link.SendControl(PacketType.Bye, reason ?? "left");

            if (IsHost && !keepRoom && !string.IsNullOrEmpty(Code) && !string.IsNullOrEmpty(secret))
            {
                var fields = new Dictionary<string, string> { { "code", Code }, { "secret", secret } };
                TeamHttp.Post("/api/team-close.php", fields).ContinueWith(t => { });
            }

            SessionState.EraseString(ResumeKey);
            EditorPrefs.DeleteKey(RejoinKey + ProjectKey);
            bool wasActive = State != TeamState.Idle;
            Close();
            Peers.Clear();

            if (wasActive && !quiet)
                AddSystem("Session ended" + (string.IsNullOrEmpty(reason) ? "." : ": " + reason));
            State = TeamState.Idle;
            if (wasActive && Ended != null)
                Ended();
            Raise();
        }

        /// <summary>Host: removes one guest from the session (the others stay).</summary>
        internal static void Kick(TeamPeer peer)
        {
            if (!IsHost || peer == null || peer.Link == null)
                return;
            peer.Link.SendControl(PacketType.Bye, "the host removed you");
            RemovePeer(peer, "Removed " + peer.Name + ".");
        }

        /// <summary>A guest left (or was lost). The host carries on with everyone else.</summary>
        private static void RemovePeer(TeamPeer peer, string note)
        {
            if (peer.Link != null)
            {
                peer.Link.Stop();
                peer.Link = null;
            }
            Peers.Remove(peer);
            if (FollowId == peer.Id)
            {
                FollowId = null;
                Following = false;
            }

            var was = Sender;
            Sender = peer;
            try
            {
                if (PeerLeft != null)
                    PeerLeft();
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                Sender = was;
            }

            if (!string.IsNullOrEmpty(note))
                AddSystem(note);
            if (IsHost)
            {
                SendRoster();
                UpdateHostState();
            }
            TeamView.SelectionChanged();
            TeamLocks.RemoteSelectionChanged();
            Raise();
        }

        // ---- Sending ------------------------------------------------------------------------------------------------

        /// <summary>Sends a message reliably and in order to everyone linked. The blob is optional raw data (file contents).</summary>
        internal static void Send(TeamMessage message, byte[] blob = null)
        {
            if (message == null)
                return;
            byte[] json = null;
            foreach (var peer in Peers)
            {
                if (peer.Link == null)
                    continue;
                if (json == null)
                    json = TeamPacket.Encode(message);
                peer.Link.Send(json, blob);
            }
        }

        /// <summary>Sends to one teammate. Teammates reached through the host can't be sent to directly.</summary>
        internal static void SendTo(TeamPeer peer, TeamMessage message, byte[] blob = null)
        {
            if (message == null || peer == null)
                return;
            string to = null;
            if (peer.Link == null)
            {
                // Another guest: through the host, addressed to them.
                to = peer.Id;
                peer = IsHost ? null : HostPeer;
            }
            if (peer == null || peer.Link == null)
                return;
            string was = message.to;
            message.to = to ?? string.Empty;
            try
            {
                peer.Link.Send(TeamPacket.Encode(message), blob);
            }
            finally
            {
                message.to = was;
            }
        }

        /// <summary>Host: passes a message from one guest to another, as theirs.</summary>
        internal static void Forward(TeamPeer to, TeamPeer from, TeamMessage message, byte[] blob = null)
        {
            if (to == null || to.Link == null || from == null || message == null)
                return;
            var copy = Tag(from, message);
            copy.to = string.Empty;
            to.Link.Send(TeamPacket.Encode(copy), blob);
        }

        /// <summary>Answers whoever sent the message being handled (everyone when there is none).</summary>
        internal static void Reply(TeamMessage message, byte[] blob = null)
        {
            if (Sender != null)
                SendTo(Sender, message, blob);
            else
                Send(message, blob);
        }

        /// <summary>Sends to everyone linked except one teammate (used by the host to pass a guest's change on).</summary>
        internal static void SendExcept(TeamPeer except, TeamMessage message, byte[] blob = null)
        {
            if (message == null)
                return;
            byte[] json = null;
            foreach (var peer in Peers)
            {
                if (peer.Link == null || peer == except)
                    continue;
                if (json == null)
                    json = TeamPacket.Encode(message);
                peer.Link.Send(json, blob);
            }
        }

        internal static void SendChat(string text)
        {
            text = (text ?? string.Empty).Trim();
            if (text.Length == 0 || !IsLinked)
                return;
            if (text.Length > 500)
                text = text.Substring(0, 500);

            Send(new TeamMessage { t = "chat", m = text });
            Chat.Add(new TeamChatLine { Name = DisplayName, Text = text, Mine = true, Time = DateTime.Now.ToString("HH:mm"), Color = LocalColor });
            TrimChat();
            Raise();
        }

        internal static void SendPing(Vector3 position)
        {
            Pings.Add(new TeamPing { Position = position, Name = DisplayName, Mine = true, Time = Now, Color = LocalColor });
            if (IsLinked)
                Send(new TeamMessage { t = "ping", p = new[] { position.x, position.y, position.z } });
            Raise();
        }

        internal static void AddSystem(string text)
        {
            Chat.Add(new TeamChatLine { Text = text, System = true, Time = DateTime.Now.ToString("HH:mm") });
            TrimChat();
            Raise();
        }

        // ---- Network setup ------------------------------------------------------------------------------------------

        private static void Prepare()
        {
            if (!Bind(Port))
                return;

            localEpoch = NewEpoch();
            State = TeamState.Preparing;
            Status = "Getting ready...";
            prepareStarted = Now;
            localIp = TeamAddress.LocalIp();
            Step("Opened port " + BoundPort + (localIp != null ? " on " + localIp : string.Empty));

            stunFinished = false;
            stunResult = null;
            stunIndex = 0;
            stunSentAt = -10;
            stunLookup = Task.Run(() => TeamStun.Servers.Select(s => TeamAddress.Parse(s)).Where(e => e != null).ToArray());

            string ip = localIp;
            int port = BoundPort;
            upnpTask = ip != null ? Task.Run(() => TeamUpnp.TryOpen(port, ip)) : null;
            Raise();
        }

        private static bool Bind(int port)
        {
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                try
                {
                    socket.Bind(new IPEndPoint(IPAddress.Any, port));
                }
                catch (SocketException)
                {
                    socket.Close();
                    socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    socket.Bind(new IPEndPoint(IPAddress.Any, 0));
                }

                socket.Blocking = false;
                socket.ReceiveBufferSize = 4 * 1024 * 1024;
                socket.SendBufferSize = 1024 * 1024;
                if (Application.platform == RuntimePlatform.WindowsEditor)
                {
                    try
                    {
                        socket.IOControl(-1744830452, new byte[] { 0, 0, 0, 0 }, null);
                    }
                    catch (Exception)
                    {
                    }
                }

                BoundPort = ((IPEndPoint)socket.LocalEndPoint).Port;
                mux = new TeamMux(socket);
                mux.Start();
                return true;
            }
            catch (Exception e)
            {
                Fail("Could not open a network port: " + e.Message);
                return false;
            }
        }

        private static double lastCrashSave = -100;

        private static void Update()
        {
            if (State == TeamState.Idle)
                return;

            // Saved every so often, so if Unity crashes it rejoins on its own when opened again (like after closing it).
            if (Peers.Any(p => p.Link != null) && !suspending && Now - lastCrashSave > 20)
            {
                lastCrashSave = Now;
                try
                {
                    var saved = Snapshot();
                    saved.files = SessionState.GetString(TeamFiles.SavedKey, string.Empty);
                    EditorPrefs.SetString(RejoinKey + ProjectKey, JsonUtility.ToJson(saved));
                }
                catch (Exception)
                {
                }
            }

            if (socket == null)
                return;

            Receive();
            if (State == TeamState.Idle)
                return;

            UpdateLinks();
            if (State == TeamState.Idle || socket == null)
                return;

            switch (State)
            {
                case TeamState.Preparing:
                    UpdatePrepare();
                    break;
                case TeamState.Connecting:
                    UpdatePunch();
                    break;
            }

            // The host keeps its invite open and connects to anyone who joins, while there is room.
            if (IsHost && State != TeamState.Preparing)
            {
                if (joining != null)
                    UpdatePunch();
                UpdateWaiting();
            }

            if (socket != null)
                CheckRequest();
        }

        private static void UpdatePrepare()
        {
            if (!stunFinished)
            {
                if (stunServers == null && stunLookup != null && stunLookup.IsCompleted)
                    stunServers = stunLookup.Status == TaskStatus.RanToCompletion ? stunLookup.Result : new IPEndPoint[0];

                if (stunServers != null && stunServers.Length > 0 && Now - stunSentAt > 0.5)
                {
                    var server = stunServers[stunIndex % stunServers.Length];
                    stunIndex++;
                    SendRaw(TeamStun.Request(out stunTransaction), server);
                    stunSentAt = Now;
                }

                if (stunServers != null && stunServers.Length == 0)
                    stunFinished = true;
            }

            bool upnpDone = upnpTask == null || upnpTask.IsCompleted;
            bool timedOut = Now - prepareStarted > PrepareTimeout;
            if (!(stunFinished && upnpDone) && !timedOut)
                return;

            if (upnpTask != null && upnpTask.IsCompleted && upnpTask.Status == TaskStatus.RanToCompletion)
                upnp = upnpTask.Result;

            Step(stunResult != null ? "Found your internet address" : "Could not find your internet address (will still try)");
            Step(upnp != null ? "Your router opened the port automatically" : "Router did not open the port automatically (that is fine)");

            if (IsHost)
            {
                if (!ApplyTakeover())
                {
                    Status = "Starting the session...";
                    RegisterInvite();
                }
            }
            else
            {
                var fields = AddressFields();
                fields["code"] = Code;
                Status = "Looking up session " + Code + "...";
                StartRequest("join", "/api/team-join.php", fields);
            }

            State = TeamState.Waiting;
            Raise();
        }

        private static Dictionary<string, string> AddressFields()
        {
            return new Dictionary<string, string>
            {
                { "name", DisplayName },
                { "password", password },
                { "public_addr", stunResult != null ? TeamAddress.Format(stunResult) : string.Empty },
                { "local_addr", localIp != null ? localIp + ":" + BoundPort : string.Empty }
            };
        }

        /// <summary>Asks reqid.io for an invite code (again when the old one expires, so more people can still join).</summary>
        private static void RegisterInvite()
        {
            StartRequest("host", "/api/team-host.php", AddressFields());
        }

        private static void UpdateWaiting()
        {
            if (!IsHost || string.IsNullOrEmpty(secret) || request != null || Now - lastPoll < 1.0 || socket == null || !HasRoom || handingOff)
                return;

            lastPoll = Now;
            StartRequest("poll", "/api/team-poll.php", new Dictionary<string, string>
            {
                { "code", Code },
                { "secret", secret },
                { "public_addr", stunResult != null ? TeamAddress.Format(stunResult) : string.Empty }
            });
        }

        private static void StartRequest(string kind, string path, Dictionary<string, string> fields)
        {
            requestKind = kind;
            request = TeamHttp.Post(path, fields);
        }

        private static void CheckRequest()
        {
            if (request == null || !request.IsCompleted)
                return;

            var finished = request;
            string kind = requestKind;
            request = null;

            if (finished.Status != TaskStatus.RanToCompletion)
            {
                string why = finished.Exception != null ? finished.Exception.GetBaseException().Message : "unknown error";
                if (kind == "poll")
                    return;
                if (kind == "host" && renewing)
                {
                    renewing = false;
                    return;
                }
                Fail("Could not reach " + WPFMAArchive.BaseUrl + ": " + why);
                return;
            }

            TeamReply reply;
            try
            {
                reply = JsonUtility.FromJson<TeamReply>(finished.Result);
            }
            catch (Exception)
            {
                reply = null;
            }

            if (reply == null || !reply.ok)
            {
                string why = reply != null && !string.IsNullOrEmpty(reply.message) ? reply.message : "The server gave an unexpected answer.";
                if (kind == "poll")
                {
                    // Invite codes only last a while on the server: get a fresh one so people can still join.
                    if (reply != null && reply.error == "team_not_found" && !renewing)
                    {
                        renewing = true;
                        secret = null;
                        RegisterInvite();
                    }
                    return;
                }
                if (kind == "host" && renewing)
                {
                    renewing = false;
                    AddSystem("Could not make a new invite code (" + why + "). Everyone already here stays connected.");
                    return;
                }
                Fail(why);
                return;
            }

            switch (kind)
            {
                case "host":
                {
                    string old = Code;
                    Code = reply.code;
                    secret = reply.secret;
                    seenIp = reply.seen_ip;
                    peerKey = reply.peer_key;
                    handledGuestAt = 0;
                    if (renewing && !string.IsNullOrEmpty(old) && old != Code)
                        AddSystem("The invite code expired, so there is a new one: " + Code + ".");
                    renewing = false;
                    if (Peers.Count == 0)
                    {
                        State = TeamState.Waiting;
                        Status = WaitingText();
                    }
                    Step("Session " + Code + " is open");
                    break;
                }

                case "poll":
                    if (reply.waiting || reply.guest_at == handledGuestAt || !HasRoom)
                        break;
                    // A new join while still connecting: give the current attempt a fair chance first.
                    if (joining != null && Now - joining.Started < 5.0)
                        break;
                    handledGuestAt = reply.guest_at;
                    if (!string.IsNullOrEmpty(reply.peer_key))
                        peerKey = reply.peer_key;
                    BeginPunch(Candidates(reply.guest_public, reply.guest_local, reply.guest_seen_ip), reply.guest_name, Code, peerKey);
                    Step(reply.guest_name + " is joining");
                    break;

                case "join":
                    peerKey = reply.peer_key;
                    seenIp = reply.seen_ip;
                {
                    var candidates = Candidates(reply.host_public, reply.host_local, reply.host_seen_ip);
                    AddHandoffHint(candidates);
                    BeginPunch(candidates, reply.host_name, Code, peerKey);
                    Step("Found " + reply.host_name + "'s session");
                }
                    break;
            }

            Raise();
        }

        private static List<IPEndPoint> Candidates(string publicAddress, string localAddress, string seen)
        {
            var list = new List<IPEndPoint>();
            var pub = TeamAddress.Parse(publicAddress);
            var local = TeamAddress.Parse(localAddress);

            IPAddress seenAddress;
            bool sameNetwork = !string.IsNullOrEmpty(seenIp) && seenIp == seen;

            if (local != null && sameNetwork)
                list.Add(local);
            if (pub != null)
                list.Add(pub);
            if (IPAddress.TryParse(seen ?? string.Empty, out seenAddress) && seenAddress.AddressFamily == AddressFamily.InterNetwork)
            {
                if (pub != null)
                    list.Add(new IPEndPoint(seenAddress, pub.Port));
                if (local != null)
                    list.Add(new IPEndPoint(seenAddress, local.Port));
            }
            if (local != null && !sameNetwork)
                list.Add(local);

            return list.GroupBy(e => e.ToString()).Select(g => g.First()).ToList();
        }

        private static void BeginPunch(List<IPEndPoint> candidates, string name, string code, string key)
        {
            if (localEpoch == 0)
                localEpoch = NewEpoch();
            var attempt = new JoinAttempt { Candidates = candidates, Started = Now, Name = name, Code = code, Key = key };
            foreach (var candidate in candidates)
            {
                if (TeamAddress.IsPrivate(candidate.Address))
                    continue;
                for (int step = 1; step <= 12; step++)
                {
                    int port = candidate.Port + step;
                    if (port <= 65535 && !candidates.Any(c => c.Address.Equals(candidate.Address) && c.Port == port))
                        attempt.Predicted.Add(new IPEndPoint(candidate.Address, port));
                }
            }
            attempt.Predicted = attempt.Predicted.GroupBy(e => e.ToString()).Select(g => g.First()).ToList();
            joining = attempt;

            if (!IsHost)
            {
                State = TeamState.Connecting;
                Status = "Connecting to " + (string.IsNullOrEmpty(name) ? "the host" : name) + "...";
            }
            Step("Trying " + candidates.Count + " way(s) to reach " + (string.IsNullOrEmpty(name) ? "each other" : name));
            Raise();
        }

        private static void UpdatePunch()
        {
            var attempt = joining;
            if (attempt == null)
                return;

            if (Now - attempt.LastPunch >= 0.2)
            {
                attempt.LastPunch = Now;
                var hello = TeamPacket.Build(PacketType.Hello, 0, HelloMessage(attempt.Code, attempt.Key));
                foreach (var candidate in attempt.Candidates)
                    SendRaw(hello, candidate);
            }

            // Some routers give every destination its own port, usually the next few. Knock on those too.
            if (attempt.Predicted.Count > 0 && Now - attempt.Started > 2.0 && Now - attempt.LastPredicted >= 0.5)
            {
                attempt.LastPredicted = Now;
                var hello = TeamPacket.Build(PacketType.Hello, 0, HelloMessage(attempt.Code, attempt.Key));
                foreach (var candidate in attempt.Predicted)
                    SendRaw(hello, candidate);
            }

            if (Now - attempt.Started > PunchTimeout)
            {
                joining = null;
                if (IsHost)
                {
                    // Keep the session open: they can press Join again, or someone else can join.
                    string who = string.IsNullOrEmpty(attempt.Name) ? "Your friend" : attempt.Name;
                    AddSystem("Could not reach " + who + " directly (one of your routers blocks it). The session is still open; " +
                              "they can press Join again. If it keeps failing, both install Tailscale (free) and use 'Join by address'.");
                    Raise();
                    return;
                }
                Fail("Could not connect directly. Your internet (or theirs) blocks this. Press Join to try again; if it keeps " +
                     "failing, both install Tailscale (free), then use 'Join by address' with the host's Tailscale IP and port " + BoundPort + ".");
            }
        }

        private static TeamMessage HelloMessage(string code, string key)
        {
            return new TeamMessage
            {
                t = "hello",
                code = code,
                key = key ?? string.Empty,
                name = DisplayName,
                pwd = PasswordHash(code, password),
                s = SceneName(),
                n = localEpoch,
                mt = TeamPacket.Protocol,
                m = TeamPacket.SdkVersion,
                g = LocalId
            };
        }

        private static double lastVersionNote = -100;

        private static string VersionProblem(TeamMessage message)
        {
            if (!string.IsNullOrEmpty(message.m) && message.m == TeamPacket.SdkVersion)
                return "Your friend's WPFMA-SDK " + message.m + " is a different build than yours (Team " + (message.mt ?? "older") + " vs " +
                       TeamPacket.Protocol + "). Both of you need to install the same, newest WPFMA-SDK download.";
            return "Your friend's WPFMA-SDK (" + (string.IsNullOrEmpty(message.m) ? "an older version" : message.m) + ") doesn't match yours (" +
                   TeamPacket.SdkVersion + "). Both of you need the same WPFMA-SDK version to work together.";
        }

        /// <summary>Handshake packets nobody's link wanted: people joining, and internet address lookups.</summary>
        private static void Receive()
        {
            MuxPacket packet;
            while (mux != null && mux.Unrouted.TryDequeue(out packet))
            {
                var data = packet.Data;
                var from = packet.From;

                if (TeamStun.IsStun(data, packet.Length))
                {
                    if (!stunFinished && stunTransaction != null)
                    {
                        var mapped = TeamStun.ParseResponse(data, packet.Length, stunTransaction);
                        if (mapped != null)
                        {
                            stunResult = mapped;
                            stunFinished = true;
                        }
                    }
                    continue;
                }

                PacketType type;
                uint seq;
                byte[] body;
                if (!TeamPacket.Parse(data, packet.Length, out type, out seq, out body))
                    continue;
                if (type != PacketType.Hello && type != PacketType.HelloAck)
                    continue;

                var message = TeamPacket.Json(body);
                if (message == null || string.IsNullOrEmpty(Code))
                    continue;
                bool ours = NormalizeCode(message.code) == Code || Peers.Any(p => p.Code == NormalizeCode(message.code));
                if (!ours)
                    continue;

                if (message.mt != TeamPacket.Protocol)
                {
                    // Different Team code on the other PC: tell both sides clearly instead of half-working.
                    if (IsHost)
                    {
                        if (type == PacketType.Hello && !string.IsNullOrEmpty(message.mt))
                            SendRaw(TeamPacket.Build(PacketType.HelloAck, 0, HelloMessage(message.code, message.key)), from);
                        if (Now - lastVersionNote > 10)
                        {
                            lastVersionNote = Now;
                            AddSystem((message.name ?? "Someone") + " tried to join, but their " + VersionProblem(message).Substring("Your friend's ".Length));
                        }
                        continue;
                    }
                    if (State == TeamState.Connecting)
                    {
                        Fail(VersionProblem(message));
                        return;
                    }
                    continue;
                }

                // Our own hello coming back: after a handoff the invite still lists the old host's home address, which
                // can be this PC. Never connect to ourselves.
                if (message.g == LocalId)
                    continue;

                if (IsHost)
                    HostHello(type, message, from);
                else if (GuestHello(type, message, from))
                    return;
            }
        }

        private static void HostHello(PacketType type, TeamMessage message, IPEndPoint from)
        {
            if (State == TeamState.Idle || State == TeamState.Preparing || message.n == 0 || string.IsNullOrEmpty(message.g))
                return;
            bool keyOk = !string.IsNullOrEmpty(peerKey) && message.key == peerKey;
            bool passwordOk = string.IsNullOrEmpty(password) || message.pwd == PasswordHash(message.code, password);
            if (!keyOk && !passwordOk)
                return;

            var existing = FindPeer(message.g);
            if (existing != null && existing.Link != null && existing.Link.Running)
                return; // their link handles it

            if (existing == null && !HasRoom)
            {
                var full = HelloMessage(message.code, message.key);
                full.reason = "full";
                SendRaw(TeamPacket.Build(PacketType.HelloAck, 0, full), from);
                if (Now - lastFullNote > 15)
                {
                    lastFullNote = Now;
                    AddSystem((message.name ?? "Someone") + " tried to join, but the session is full (" + (MaxGuests + 1) + " people).");
                }
                return;
            }

            if (type == PacketType.Hello)
            {
                var ack = TeamPacket.Build(PacketType.HelloAck, 0, HelloMessage(message.code, message.key));
                SendRaw(ack, from);
                SendRaw(ack, from);
            }

            if (existing != null)
                RemovePeer(existing, null);
            if (joining != null && (joining.Name == message.name || joining.Candidates.Any(c => c.Address.Equals(from.Address))))
                joining = null;

            if (string.IsNullOrEmpty(peerKey))
                peerKey = Guid.NewGuid().ToString("N");
            var peer = AddPeer(message.g, message.name);
            peer.Code = NormalizeCode(message.code);
            peer.Key = peerKey;
            Connect(peer, message, from);
        }

        /// <summary>A guest hears back from the host. True when connected (or failed) and the rest can wait.</summary>
        private static bool GuestHello(PacketType type, TeamMessage message, IPEndPoint from)
        {
            if (State != TeamState.Connecting || joining == null || message.n == 0 || string.IsNullOrEmpty(message.g))
                return false;
            if (NormalizeCode(message.code) != Code)
                return false;

            bool valid = (!string.IsNullOrEmpty(peerKey) && message.key == peerKey) || joining.Candidates.Any(c => c.Equals(from));
            if (!valid)
                return false;

            if (message.reason == "full")
            {
                Fail((message.name ?? "The host") + "'s session is full (" + (MaxGuests + 1) + " people at most). Ask them to make room, then join again.");
                return true;
            }

            if (type == PacketType.Hello)
            {
                var ack = TeamPacket.Build(PacketType.HelloAck, 0, HelloMessage(Code, peerKey));
                SendRaw(ack, from);
                SendRaw(ack, from);
            }

            joining = null;
            var host = AddPeer(message.g, message.name);
            host.IsHost = true;
            host.Code = Code;
            host.Key = peerKey;
            Connect(host, message, from);
            return true;
        }

        private static void Connect(TeamPeer peer, TeamMessage hello, IPEndPoint endpoint)
        {
            peer.Remote = endpoint;
            peer.Scene = hello.s;
            if (!string.IsNullOrEmpty(hello.name))
                peer.Name = hello.name;

            StartLink(peer, hello.n, false);
            peer.Up = true;
            State = TeamState.Connected;
            Error = null;
            Step("Connected to " + peer.Name);
            if (IsHost)
            {
                Status = ConnectedText();
                AddSystem(peer.Name + " joined. Their camera shows in your Scene view in " + ColorName(peer.Color) + ", with an arrow where they look.");
                SendTo(peer, new TeamMessage { t = "key", key = peerKey });
                SendRoster();
                // What the others are doing right now, so the newcomer sees them straight away.
                foreach (var other in Peers)
                    if (other != peer)
                        foreach (var presence in other.LastPresence.Values)
                            SendTo(peer, presence);
            }
            else
            {
                Status = "Connected to " + peer.Name;
                AddSystem("Connected to " + peer.Name + ". Their camera shows in your Scene view in " + ColorName(peer.Color) + ", with an arrow where they look.");
            }

            AfterLinkUp(peer, false);
        }

        private static string ColorName(Color color)
        {
            int index = Array.IndexOf(Palette, color);
            switch (index)
            {
                case 1: return "green";
                case 2: return "purple";
                case 3: return "pink";
                default: return "orange";
            }
        }

        private static void StartLink(TeamPeer peer, int remoteEpoch, bool resuming)
        {
            peer.Link = new TeamLink(socket, mux, peer.Id, peer.Remote, localEpoch, remoteEpoch, peer.Code ?? Code, peer.Key ?? peerKey,
                HelloMessage(peer.Code ?? Code, peer.Key ?? peerKey), resuming);
            peer.Link.Start();
        }

        /// <summary>Host: tells every guest who else is in the session.</summary>
        private static void SendRoster()
        {
            if (!IsHost)
                return;
            var guests = Peers.Where(p => p.Link != null).ToList();
            Send(new TeamMessage { t = "peers", a = guests.Select(p => p.Id).ToArray(), b = guests.Select(p => p.Name).ToArray() });
        }

        private static void UpdateHostState()
        {
            if (!IsHost || State == TeamState.Idle || State == TeamState.Preparing)
                return;
            var linked = Peers.Where(p => p.Link != null).ToList();
            if (linked.Count == 0)
            {
                State = TeamState.Waiting;
                Status = WaitingText();
            }
            else if (linked.Any(p => p.Up))
            {
                State = TeamState.Connected;
                Status = ConnectedText();
            }
            else
            {
                State = TeamState.Reconnecting;
                Status = "Reconnecting to " + RemoteName + "...";
            }
        }

        private static string WaitingText()
        {
            if (string.IsNullOrEmpty(secret) && !string.IsNullOrEmpty(Code) && localIp != null)
                return "Waiting for someone to join " + localIp + ":" + BoundPort + " with code " + Code;
            return "Waiting for someone to join with code " + Code;
        }

        private static string ConnectedText()
        {
            return "Connected to " + RemoteName + (HasRoom ? "  ·  invite code " + Code : string.Empty);
        }

        private static void AfterLinkUp(TeamPeer peer, bool resumed)
        {
            RejoinDone();
            lastCameraSent = -10;
            SendScene();
            OnSelectionChanged();
            Send(TeamLook.Message());
            lastActivity = null;
            var was = Sender;
            Sender = peer;
            try
            {
                if (LinkUp != null)
                {
                    foreach (Action<bool> handler in LinkUp.GetInvocationList())
                    {
                        try
                        {
                            handler(resumed);
                        }
                        catch (Exception e)
                        {
                            Debug.LogException(e);
                        }
                    }
                }
            }
            finally
            {
                Sender = was;
            }
            Raise();
        }

        private static void UpdateLinks()
        {
            foreach (var peer in Peers.Where(p => p.Link != null).ToList())
            {
                LinkEvent linkEvent;
                while (peer.Link != null && peer.Link.Events.TryDequeue(out linkEvent))
                {
                    if (!HandleLinkEvent(peer, linkEvent))
                        return;
                }
            }

            if (State != TeamState.Connected)
                return;

            // Messages from everyone, in turn, a few milliseconds per frame.
            double started = Now;
            bool any = true;
            while (any && Now - started < 0.03)
            {
                any = false;
                foreach (var peer in Peers.Where(p => p.Link != null && p.Up).ToList())
                {
                    LinkInbound inbound;
                    if (peer.Link == null || !peer.Link.Inbox.TryDequeue(out inbound))
                        continue;
                    any = true;
                    var message = TeamPacket.Json(inbound.Json);
                    if (message != null)
                        Dispatch(peer, message, inbound.Blob);
                    if (State != TeamState.Connected)
                        return;
                }
            }

            SendCamera();
            SendActivity();
            SendState();
            Pings.RemoveAll(p => Now - p.Time > 5.0);
        }

        /// <summary>False when the session ended and nothing else should be processed this frame.</summary>
        private static bool HandleLinkEvent(TeamPeer peer, LinkEvent linkEvent)
        {
            switch (linkEvent.Kind)
            {
                case LinkEventKind.Up:
                    peer.Remote = peer.Link.Remote;
                    peer.Up = true;
                    State = TeamState.Connected;
                    Status = IsHost ? ConnectedText() : "Connected to " + peer.Name;
                    AddSystem(peer.RestartPending ? "Rejoined " + (IsHost ? peer.Name : peer.Name + "'s session") + "." : "Reconnected to " + peer.Name + ".");
                    TeamToasts.Show(peer.RestartPending ? "Rejoined " + peer.Name : "Reconnected to " + peer.Name);
                    AfterLinkUp(peer, true);
                    if (peer.RestartPending)
                    {
                        peer.RestartPending = false;
                        SendTo(peer, new TeamMessage { t = "restart" });
                        if (rejoined)
                        {
                            rejoined = false;
                            if (Restarted != null)
                                Restarted();
                        }
                    }
                    if (IsHost)
                        SendRoster();
                    return true;

                case LinkEventKind.Reconnecting:
                    peer.Up = false;
                    AddSystem("The connection to " + peer.Name + " dropped. Trying to reconnect for up to 10 minutes (if their Unity crashed, " +
                              "it rejoins by itself when they open it again). Nothing you change is lost.");
                    TeamToasts.Show("Connection to " + peer.Name + " dropped - reconnecting");
                    if (IsHost)
                        UpdateHostState();
                    else
                    {
                        State = TeamState.Reconnecting;
                        Status = "Lost the connection to " + peer.Name + ". Reconnecting...";
                    }
                    Raise();
                    return true;

                case LinkEventKind.PeerResumed:
                    peer.Remote = peer.Link.Remote;
                    peer.Up = true;
                    State = TeamState.Connected;
                    Status = IsHost ? ConnectedText() : "Connected to " + peer.Name;
                    AddSystem(peer.Name + " is back.");
                    TeamToasts.Show(peer.Name + " is back");
                    AfterLinkUp(peer, true);
                    return true;

                case LinkEventKind.PeerHold:
                    if (linkEvent.Text == "closed Unity")
                        AddSystem(peer.Name + " closed Unity. Waiting up to " + RejoinMinutes + " minutes for them to come back" +
                                  (IsHost ? "; the others carry on." : "; press Leave to stop waiting."));
                    else
                        AddSystem(peer.Name + "'s Unity is " + (string.IsNullOrEmpty(linkEvent.Text) ? "busy" : linkEvent.Text) + ". Waiting for it...");
                    Raise();
                    return true;

                case LinkEventKind.Lost:
                    if (IsHost)
                    {
                        RemovePeer(peer, "Lost " + peer.Name + " (" + linkEvent.Text + ").");
                        return true;
                    }
                    Leave(linkEvent.Text + " with " + peer.Name);
                    return false;

                case LinkEventKind.Bye:
                {
                    string reason = string.IsNullOrEmpty(linkEvent.Text) ? "left" : linkEvent.Text;
                    if (IsHost)
                    {
                        RemovePeer(peer, peer.Name + " left (" + reason + ").");
                        return true;
                    }
                    string name = peer.Name;
                    Leave(name + " ended the session (" + reason + ")", true);
                    AddSystem(name + " ended the session (" + reason + ").");
                    return false;
                }
            }
            return true;
        }

        // Presence and chat the host passes on from one guest to the others. Scene edits ("op") too.
        private static readonly HashSet<string> Relayed = new HashSet<string> { "cam", "sel", "scene", "act", "upl", "ping", "chat", "op", "ops", "look", "state" };

        private static void Dispatch(TeamPeer peer, TeamMessage message, byte[] blob, bool relay = true)
        {
            // Host: a guest's message for another guest (a scene only the two of them have open) is passed straight on.
            if (IsHost && relay && !string.IsNullOrEmpty(message.to) && message.to != LocalId)
            {
                Forward(FindPeer(message.to), peer, message, blob);
                return;
            }

            // On a guest, a message passed on by the host may be about another guest.
            var origin = peer;
            if (!IsHost && !string.IsNullOrEmpty(message.g) && message.g != peer.Id && message.g != LocalId)
                origin = AddPeer(message.g, message.name);

            if (relay && IsHost && Relayed.Contains(message.t))
                Relay(peer, message, blob);

            switch (message.t)
            {
                case "ops":
                {
                    // Several scene edits in one message: each is handled as if it came on its own.
                    TeamBundle bundle = null;
                    try
                    {
                        bundle = JsonUtility.FromJson<TeamBundle>(message.json);
                    }
                    catch (Exception)
                    {
                    }
                    if (bundle == null || bundle.list == null)
                        return;
                    foreach (var inner in bundle.list)
                    {
                        if (inner == null)
                            continue;
                        TeamPacket.Filled(inner);
                        inner.g = message.g;
                        if (string.IsNullOrEmpty(inner.name))
                            inner.name = message.name;
                        Dispatch(peer, inner, null, false);
                        if (State != TeamState.Connected)
                            return;
                    }
                    return;
                }
                case "cam":
                    if (message.p != null && message.p.Length == 3 && message.r != null && message.r.Length == 4)
                    {
                        origin.CameraPosition = new Vector3(message.p[0], message.p[1], message.p[2]);
                        origin.CameraRotation = new Quaternion(message.r[0], message.r[1], message.r[2], message.r[3]);
                        origin.HasCamera = true;
                        TeamView.RemoteMoved(origin);
                    }
                    return;
                case "sel":
                    origin.Selection = message.paths ?? new string[0];
                    origin.SelectionIds = message.a ?? new string[0];
                    if (!string.IsNullOrEmpty(message.s))
                        origin.Scene = message.s;
                    TeamView.SelectionChanged();
                    TeamLocks.RemoteSelectionChanged();
                    Raise();
                    return;
                case "scene":
                    origin.Scene = message.s;
                    if (origin.ScenePath != message.f)
                        origin.SceneSince = Now;
                    origin.ScenePath = message.f;
                    origin.Playing = message.o;
                    origin.Prefab = string.IsNullOrEmpty(message.m) ? null : message.m;
                    Raise();
                    // Guests only follow the host's scene, not another guest's.
                    if (origin != peer)
                        return;
                    break;
                case "restart":
                {
                    var was = Sender;
                    Sender = origin;
                    try
                    {
                        if (PeerRestarted != null)
                            PeerRestarted();
                    }
                    finally
                    {
                        Sender = was;
                    }
                    return;
                }
                case "look":
                    TeamLook.Receive(origin, message);
                    return;
                case "state":
                    ReceiveState(origin, message);
                    return;
                case "handoff":
                    OnHandoff(peer, message);
                    return;
                case "newhost":
                    OnNewHost(peer, message);
                    return;
                case "act":
                    origin.Window = message.m;
                    origin.Asset = string.IsNullOrEmpty(message.f) ? null : message.f;
                    Raise();
                    EditorApplication.RepaintProjectWindow();
                    return;
                case "upl":
                    origin.UploadAt = Now;
                    origin.UploadKind = message.m;
                    AddSystem(origin.Name + " started building/uploading the " + (message.m ?? "project") + ".");
                    TeamToasts.Show(origin.Name + " is uploading");
                    return;
                case "ping":
                    if (message.p != null && message.p.Length == 3)
                    {
                        Pings.Add(new TeamPing { Position = new Vector3(message.p[0], message.p[1], message.p[2]), Name = origin.Name, Time = Now, Color = origin.Color });
                        Raise();
                    }
                    return;
                case "chat":
                    if (!string.IsNullOrEmpty(message.m))
                    {
                        Chat.Add(new TeamChatLine
                        {
                            Name = origin.Name,
                            Text = message.m.Length > 500 ? message.m.Substring(0, 500) : message.m,
                            Time = DateTime.Now.ToString("HH:mm"),
                            Color = origin.Color
                        });
                        TrimChat();
                        Unread++;
                        TeamToasts.Show(origin.Name + ": " + (message.m.Length > 60 ? message.m.Substring(0, 60) + "..." : message.m));
                        Raise();
                    }
                    return;
                case "key":
                    if (!IsHost && !string.IsNullOrEmpty(message.key) && peer.Link != null)
                    {
                        peerKey = message.key;
                        peer.Key = peerKey;
                        peer.Link.Key = peerKey;
                    }
                    return;
                case "peers":
                    if (!IsHost)
                        ApplyRoster(message);
                    return;
            }

            if (Received != null)
            {
                var was = Sender;
                Sender = origin;
                try
                {
                    Received(message, blob);
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                }
                finally
                {
                    Sender = was;
                }
            }
        }

        /// <summary>Host: passes a guest's presence, chat or scene edit on to the other guests.</summary>
        private static void Relay(TeamPeer from, TeamMessage message, byte[] blob)
        {
            if (Peers.Count(p => p.Link != null) < 2)
            {
                if (message.t == "sel" || message.t == "scene" || message.t == "act" || message.t == "look" || message.t == "state")
                    from.LastPresence[message.t] = Tag(from, message);
                return;
            }
            var copy = Tag(from, message);
            if (message.t == "sel" || message.t == "scene" || message.t == "act" || message.t == "look" || message.t == "state")
                from.LastPresence[message.t] = copy;
            if (message.t == "cam")
            {
                var json = TeamPacket.Encode(copy);
                foreach (var peer in Peers)
                    if (peer != from && peer.Link != null)
                        peer.Link.SendLossy(json);
                return;
            }
            SendExcept(from, copy, blob);
        }

        private static TeamMessage Tag(TeamPeer from, TeamMessage message)
        {
            var copy = JsonUtility.FromJson<TeamMessage>(JsonUtility.ToJson(message));
            copy.g = from.Id;
            if (string.IsNullOrEmpty(copy.name))
                copy.name = from.Name;
            return copy;
        }

        /// <summary>Guest: the host's list of who else is here.</summary>
        private static void ApplyRoster(TeamMessage message)
        {
            var ids = message.a ?? new string[0];
            var names = message.b ?? new string[0];
            for (int i = 0; i < ids.Length; i++)
                if (ids[i] != LocalId)
                    AddPeer(ids[i], i < names.Length ? names[i] : null);
            foreach (var gone in Peers.Where(p => !p.IsHost && p.Link == null && !ids.Contains(p.Id)).ToList())
                RemovePeer(gone, gone.Name + " left.");
            Raise();
        }

        private static void SendCamera()
        {
            var view = SceneView.lastActiveSceneView;
            if (view == null || view.camera == null)
                return;

            var position = view.camera.transform.position;
            var rotation = view.camera.transform.rotation;
            bool moved = (position - lastCameraPosition).sqrMagnitude > 0.000001f || Quaternion.Angle(rotation, lastCameraRotation) > 0.1f;

            if (Now - lastCameraSent < (moved ? 0.05 : 1.0))
                return;

            lastCameraSent = Now;
            lastCameraPosition = position;
            lastCameraRotation = rotation;
            var json = TeamPacket.Encode(new TeamMessage
            {
                t = "cam",
                p = new[] { position.x, position.y, position.z },
                r = new[] { rotation.x, rotation.y, rotation.z, rotation.w }
            });
            foreach (var peer in Peers)
                if (peer.Link != null)
                    peer.Link.SendLossy(json);
        }

        /// <summary>Shares which window you are in and which asset you have selected, when that changes.</summary>
        private static void SendActivity()
        {
            if (Now - lastActivitySent < 0.5)
                return;
            lastActivitySent = Now;

            var window = EditorWindow.focusedWindow;
            string title = window != null ? window.titleContent.text : string.Empty;
            var active = Selection.activeObject;
            string asset = active != null && EditorUtility.IsPersistent(active) ? AssetDatabase.GetAssetPath(active) : string.Empty;
            string state = title + "|" + asset;
            if (state == lastActivity)
                return;
            lastActivity = state;
            Send(new TeamMessage { t = "act", m = title, f = asset });
        }

        private static void OnSelectionChanged()
        {
            if (!IsLinked)
                return;

            var objects = Selection.gameObjects
                .Where(g => g != null && !EditorUtility.IsPersistent(g) && g.scene.IsValid())
                .Take(50)
                .ToArray();

            Send(new TeamMessage
            {
                t = "sel",
                paths = objects.Select(TeamView.PathOf).ToArray(),
                a = objects.Select(TeamScene.IdFor).ToArray(),
                s = SceneName()
            });
        }

        private static void SendScene()
        {
            if (IsLinked)
            {
                var stage = UnityEditor.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
                Send(new TeamMessage
                {
                    t = "scene",
                    s = SceneName(),
                    f = ScenePath(),
                    o = EditorApplication.isPlayingOrWillChangePlaymode,
                    m = stage != null ? stage.assetPath : string.Empty
                });
            }
        }

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

        internal static string SceneName()
        {
            var scene = EditorSceneManager.GetActiveScene();
            return scene.IsValid() ? scene.name : string.Empty;
        }

        internal static string ScenePath()
        {
            var scene = EditorSceneManager.GetActiveScene();
            return scene.IsValid() ? scene.path : string.Empty;
        }

        private static string PasswordHash(string code, string value)
        {
            if (string.IsNullOrEmpty(value))
                return string.Empty;
            using (var sha = SHA256.Create())
                return BitConverter.ToString(sha.ComputeHash(Encoding.UTF8.GetBytes(NormalizeCode(code) + "|" + value))).Replace("-", string.Empty);
        }

        internal static string NormalizeCode(string code)
        {
            return TeamPacket.NormalizeCode(code);
        }

        private static int NewEpoch()
        {
            var bytes = new byte[4];
            using (var rng = RandomNumberGenerator.Create())
            {
                int value = 0;
                while (value == 0)
                {
                    rng.GetBytes(bytes);
                    value = BitConverter.ToInt32(bytes, 0);
                }
                return value;
            }
        }

        // ---- Script reloads and Play mode -------------------------------------------------------------------------

        /// <summary>
        /// Unity is about to reload scripts (after a compile or when entering Play mode). Tell the others to wait,
        /// save what is needed to reconnect, and close the socket so the reloaded code can open it again.
        /// </summary>
        private static void Suspend()
        {
            if (SuspendHandoff())
                return;

            bool linked = Peers.Any(p => p.Link != null);

            // A host still waiting for its first guest keeps the same code and port across the reload.
            if (IsHost && !linked && !string.IsNullOrEmpty(Code) && (State == TeamState.Waiting || State == TeamState.Connecting))
            {
                SessionState.SetString(ResumeKey, JsonUtility.ToJson(new TeamSaved
                {
                    waiting = true,
                    code = Code,
                    host = true,
                    key = peerKey,
                    secret = secret,
                    password = password,
                    port = BoundPort,
                    seenIp = seenIp,
                    savedAt = DateTime.UtcNow.Ticks
                }));
                suspending = true;
                Close();
                return;
            }

            // Still getting started (finding the internet address, asking reqid.io, connecting): start it again after
            // the reload instead of quietly dropping it.
            if (!linked && (State == TeamState.Preparing || State == TeamState.Waiting || State == TeamState.Connecting))
            {
                SessionState.SetString(ResumeKey, JsonUtility.ToJson(new TeamSaved
                {
                    restart = true,
                    host = IsHost,
                    code = Code,
                    password = password,
                    address = joinAddress,
                    savedAt = DateTime.UtcNow.Ticks
                }));
                suspending = true;
                Close();
                return;
            }

            if (!linked)
            {
                Leave("Unity reloaded scripts", true);
                return;
            }

            suspending = true;
            foreach (var peer in Linked)
                peer.Link.SendControl(PacketType.Hold, EditorApplication.isPlayingOrWillChangePlaymode ? "entering Play mode" : "reloading scripts");

            RunSuspending();
            SessionState.SetString(ResumeKey, JsonUtility.ToJson(Snapshot()));
            Close();
        }

        private static void RunSuspending()
        {
            if (Suspending == null)
                return;
            foreach (Action handler in Suspending.GetInvocationList())
            {
                try
                {
                    handler();
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                }
            }
        }

        private static TeamSaved Snapshot()
        {
            var keep = Chat.Skip(Math.Max(0, Chat.Count - 60)).ToList();
            var linked = Peers.Where(p => p.Link != null).ToList();
            return new TeamSaved
            {
                code = Code,
                host = IsHost,
                key = peerKey,
                secret = secret,
                password = password,
                port = BoundPort,
                seenIp = seenIp,
                savedAt = DateTime.UtcNow.Ticks,
                peerIds = linked.Select(p => p.Id).ToArray(),
                peerNames = linked.Select(p => p.Name ?? string.Empty).ToArray(),
                peerCodes = linked.Select(p => p.Code ?? Code ?? string.Empty).ToArray(),
                peerKeys = linked.Select(p => p.Key ?? peerKey ?? string.Empty).ToArray(),
                peerRemotes = linked.Select(p => TeamAddress.Format(p.Link != null ? p.Link.Remote : p.Remote)).ToArray(),
                peerScenes = linked.Select(p => p.Scene ?? string.Empty).ToArray(),
                chatNames = keep.Select(c => c.Name ?? string.Empty).ToArray(),
                chatTexts = keep.Select(c => c.Text ?? string.Empty).ToArray(),
                chatTimes = keep.Select(c => c.Time ?? string.Empty).ToArray(),
                chatMine = keep.Select(c => c.Mine).ToArray(),
                chatSystem = keep.Select(c => c.System).ToArray()
            };
        }

        private static string ProjectKey
        {
            get
            {
                using (var md5 = MD5.Create())
                    return BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(Application.dataPath))).Replace("-", string.Empty).Substring(0, 12);
            }
        }

        /// <summary>
        /// Closing Unity does not end the session straight away: the others wait a few minutes, and if Unity is
        /// opened again in that time it rejoins on its own.
        /// </summary>
        private static void OnQuitting()
        {
            if (!Peers.Any(p => p.Link != null))
            {
                Leave("Unity closed", true);
                return;
            }

            foreach (var peer in Linked)
                peer.Link.SendControl(PacketType.Hold, ((int)(RejoinMinutes * 60)).ToString() + "|closed Unity");

            RunSuspending();

            var saved = Snapshot();
            saved.files = SessionState.GetString(TeamFiles.SavedKey, string.Empty);
            EditorPrefs.SetString(RejoinKey + ProjectKey, JsonUtility.ToJson(saved));
            suspending = true;
            Close();
        }

        private static void TryResume()
        {
            if (State != TeamState.Idle)
                return;
            // A handoff rejoin on its way takes the place of anything else saved for the reload.
            if (RestorePendingRejoin())
            {
                SessionState.EraseString(ResumeKey);
                return;
            }

            string json = SessionState.GetString(ResumeKey, string.Empty);
            bool rejoin = false;
            if (string.IsNullOrEmpty(json))
            {
                json = EditorPrefs.GetString(RejoinKey + ProjectKey, string.Empty);
                EditorPrefs.DeleteKey(RejoinKey + ProjectKey);
                rejoin = !string.IsNullOrEmpty(json);
            }
            if (string.IsNullOrEmpty(json))
                return;
            SessionState.EraseString(ResumeKey);

            TeamSaved saved;
            try
            {
                saved = JsonUtility.FromJson<TeamSaved>(json);
            }
            catch (Exception)
            {
                return;
            }

            if (saved == null)
                return;
            if (saved.restart && !rejoin)
            {
                if (ResumeTakeover(saved))
                    return;
                if (saved.host)
                    StartHost(saved.password);
                else if (!string.IsNullOrEmpty(saved.address))
                    JoinAddress(saved.address, saved.code, saved.password);
                else if (!string.IsNullOrEmpty(saved.code))
                    Join(saved.code, saved.password);
                return;
            }
            if (saved.waiting && !rejoin)
            {
                Reset();
                IsHost = true;
                Code = saved.code;
                peerKey = string.IsNullOrEmpty(saved.key) ? null : saved.key;
                secret = string.IsNullOrEmpty(saved.secret) ? null : saved.secret;
                password = saved.password ?? string.Empty;
                seenIp = saved.seenIp;
                if (!Bind(saved.port))
                    return;
                localEpoch = NewEpoch();
                localIp = TeamAddress.LocalIp();
                State = TeamState.Waiting;
                Status = WaitingText();
                Raise();
                return;
            }

            if (saved.peerIds == null || saved.peerIds.Length == 0 || string.IsNullOrEmpty(saved.code))
                return;
            if (rejoin && (DateTime.UtcNow - new DateTime(saved.savedAt, DateTimeKind.Utc)).TotalMinutes > RejoinMinutes)
                return;

            Reset();
            for (int i = 0; saved.chatTexts != null && i < saved.chatTexts.Length; i++)
            {
                Chat.Add(new TeamChatLine
                {
                    Name = saved.chatNames[i],
                    Text = saved.chatTexts[i],
                    Time = saved.chatTimes[i],
                    Mine = saved.chatMine[i],
                    System = saved.chatSystem[i]
                });
            }

            IsHost = saved.host;
            Code = saved.code;
            peerKey = saved.key;
            secret = string.IsNullOrEmpty(saved.secret) ? null : saved.secret;
            password = saved.password ?? string.Empty;
            seenIp = saved.seenIp;

            if (!Bind(saved.port))
                return;

            if (rejoin && !string.IsNullOrEmpty(saved.files))
                TeamFiles.RestoreFrom(saved.files);

            localEpoch = NewEpoch();
            localIp = TeamAddress.LocalIp();
            for (int i = 0; i < saved.peerIds.Length; i++)
            {
                var target = TeamAddress.Parse(saved.peerRemotes[i]);
                if (target == null)
                    continue;
                var peer = AddPeer(saved.peerIds[i], saved.peerNames[i]);
                peer.IsHost = !IsHost;
                peer.Code = string.IsNullOrEmpty(saved.peerCodes[i]) ? Code : saved.peerCodes[i];
                peer.Key = string.IsNullOrEmpty(saved.peerKeys[i]) ? peerKey : saved.peerKeys[i];
                peer.Remote = target;
                peer.Scene = saved.peerScenes != null && i < saved.peerScenes.Length ? saved.peerScenes[i] : null;
                peer.RestartPending = rejoin;
                StartLink(peer, 0, true);
            }
            if (!Peers.Any())
                return;

            rejoined = rejoin;
            State = TeamState.Reconnecting;
            Status = rejoin ? "Rejoining " + (IsHost ? "your session" : RemoteName + "'s session") + "..." : "Reconnecting to " + RemoteName + " after the reload...";
            Raise();
        }

        private static void Fail(string message)
        {
            Error = message;
            Status = null;
            Close();
            Peers.Clear();
            State = TeamState.Idle;
            RetryRejoin();
            Raise();
        }

        private static void Reset()
        {
            Close();
            Peers.Clear();
            Error = null;
            Status = null;
            Steps.Clear();
            Code = null;
            secret = null;
            peerKey = null;
            seenIp = null;
            localEpoch = 0;
            Pings.Clear();
            Following = false;
            FollowId = null;
            Unread = 0;
            lastActivity = null;
            stunServers = null;
            stunLookup = null;
            suspending = false;
            rejoined = false;
            renewing = false;
            handledGuestAt = 0;
            joining = null;
            joinAddress = null;
            handingOff = false;
            takeover = null;
            RejoinNote = null;
            lastStateSent = null;
            lastStateAt = -100;
        }

        private static void Close()
        {
            foreach (var peer in Peers)
            {
                if (peer.Link != null)
                {
                    peer.Link.Stop();
                    peer.Link = null;
                }
                peer.Up = false;
            }

            if (mux != null)
            {
                mux.Stop();
                mux = null;
            }

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

            request = null;
            joining = null;
            Following = false;

            var mapping = upnp;
            upnp = null;
            if (mapping != null && !suspending)
                Task.Run(() => TeamUpnp.Close(mapping));

            TeamView.SelectionChanged();
            TeamLocks.RemoteSelectionChanged();
        }

        private static void Step(string text)
        {
            Steps.Add(text);
            if (Steps.Count > 12)
                Steps.RemoveAt(0);
        }

        private static void TrimChat()
        {
            while (Chat.Count > 200)
                Chat.RemoveAt(0);
        }

        internal static void Raise()
        {
            if (Changed != null)
                Changed();
            TeamView.Repaint();
        }
    }
}
#endif
