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

namespace WPFMA.Team
{
    internal enum TeamSyncPhase
    {
        Off,
        Scanning,
        Review,
        Downloading,
        Live
    }

    internal sealed class TeamPendingCode
    {
        public string Path;
        public string Temp;
        public string Meta;
        public string Hash;
        public long Mtime;
        public long Size;
        public bool Forced;
        public string Base;
        // Which teammate sent it (the host passes it on to the others once written).
        public string From;
    }

    [Serializable]
    internal sealed class TeamPeerFilesSaved
    {
        public string id;
        public string[] awaiting;
        public string[] inPath;
        public string[] inTemp;
        public string[] inMeta;
        public long[] inMtime;
        public int[] inNext;
        public string[] inBase;
    }

    [Serializable]
    internal sealed class TeamFilesSaved
    {
        public bool live;
        public bool trust;
        public long since;
        public bool accepted;
        public TeamPeerFilesSaved[] peers;
        public string[] remoteExcluded;
        public string[] pendingPath;
        public string[] pendingTemp;
        public string[] pendingMeta;
        public string[] pendingHash;
        public long[] pendingMtime;
        public long[] pendingSize;
        public string[] pendingFrom;
    }

    /// <summary>
    /// Keeps the shared part of the Assets folder the same on both editors: a file list comparison when someone
    /// joins or reconnects, then every save, new file, delete and move as it happens. Files the other side sends
    /// that can run code wait for the "Trust code" switch. Anything overwritten or deleted is copied to
    /// WPFMA-Snapshots/Team first.
    /// </summary>
    [InitializeOnLoad]
    internal static partial class TeamFiles
    {
        private const int ChunkSize = 256 * 1024;
        private const long BacklogLimit = 12L * 1024 * 1024;
        internal const string SavedKey = "WPFMA.Team.Files";
        private const string AutoSaveKey = "WPFMA.Team.AutoSave";

        private static readonly string[] CodeExtensions =
        {
            ".cs", ".dll", ".asmdef", ".asmref", ".rsp", ".so", ".dylib", ".bundle", ".jslib", ".jspre", ".exe", ".bat",
            ".cmd", ".ps1", ".sh", ".vbs", ".js", ".jar", ".py", ".msi", ".com", ".scr", ".pyd"
        };

        private static readonly string[] AlwaysSkipped =
        {
            "Assets/WPFMA-SDK", "Assets/WPFMA-SDK-Dev", "Assets/ParrelSync"
        };

        private sealed class Entry
        {
            public string Path;
            public string Hash;
            public long Size;
            public long Mtime;
            public bool Dir;
        }

        private sealed class Incoming
        {
            public string Path;
            public string Temp;
            public string Meta;
            public long Mtime;
            public int Next;
            public FileStream Stream;
            public bool Requested;
            public bool Forced;
            public string Base;
        }

        private sealed class Outgoing
        {
            public string Path;
            public FileStream Stream;
            public MD5 Md5;
            public string Meta;
            public string MetaHash;
            public long Mtime;
            public int Index;
            public bool Forced;
            public string Base;
        }

        private sealed class CacheEntry
        {
            public long Size;
            public long Mtime;
            public string Hash;
        }

        /// <summary>
        /// What is being exchanged with one teammate. The host has one of these per guest (its own project is the
        /// hub: a file from one guest is written here, then sent on to the others); a guest has one, for the host.
        /// </summary>
        private sealed class PeerFiles
        {
            public string Id;
            /// <summary>The last version this teammate and this editor both had of each file (base for clashes and catching up).</summary>
            public readonly Dictionary<string, string> Agreed = new Dictionary<string, string>();
            public readonly List<string> SendQueue = new List<string>();
            public Outgoing Current;
            public readonly HashSet<string> ForcedSends = new HashSet<string>();
            public readonly Dictionary<string, int> StartChunk = new Dictionary<string, int>();
            public readonly Dictionary<string, string> BaseOf = new Dictionary<string, string>();
            public readonly Dictionary<string, Incoming> Incoming = new Dictionary<string, Incoming>();
            /// <summary>New files sent to this teammate that they have not confirmed yet (path -> GUID).</summary>
            public readonly Dictionary<string, string> Awaiting = new Dictionary<string, string>();
            public readonly Dictionary<string, double> AwaitingSince = new Dictionary<string, double>();
            public double CheckAnswerAt = -1;
            public string CheckResult;
            public bool AgreedLoaded;
            /// <summary>Host: a teammate we've worked with before, back after time apart; nothing is pushed until Sync.</summary>
            public bool Reuniting;
            /// <summary>The shared versions as they were when they reconnected (the merge base).</summary>
            public Dictionary<string, string> ReunionBase;

            public TeamPeer Peer
            {
                get { return TeamSession.FindPeer(Id); }
            }

            public string Name
            {
                get
                {
                    var peer = Peer;
                    return peer != null ? peer.Name : "your teammate";
                }
            }
        }

        private static readonly Dictionary<string, PeerFiles> peers = new Dictionary<string, PeerFiles>();

        /// <summary>The exchange with this teammate (made on first use). Null for teammates reached through the host.</summary>
        private static PeerFiles For(TeamPeer peer)
        {
            if (peer == null)
                return null;
            if (!peer.Linked)
                peer = TeamSession.IsHost ? null : TeamSession.HostPeer;
            if (peer == null)
                return null;
            return For(peer.Id);
        }

        private static PeerFiles For(string id)
        {
            if (string.IsNullOrEmpty(id))
                return null;
            PeerFiles pf;
            if (!peers.TryGetValue(id, out pf))
            {
                pf = new PeerFiles { Id = id };
                peers[id] = pf;
                LoadAgreed(pf);
            }
            return pf;
        }

        /// <summary>Everyone this editor exchanges files with right now.</summary>
        private static List<PeerFiles> Linked
        {
            get { return TeamSession.Linked.Select(p => For(p.Id)).ToList(); }
        }

        private static void SendTo(PeerFiles pf, TeamMessage message, byte[] blob = null)
        {
            var peer = pf != null ? pf.Peer : null;
            if (peer != null)
                TeamSession.SendTo(peer, message, blob);
        }

        internal static TeamSyncPhase Phase { get; private set; }
        internal static string PhaseText { get; private set; }
        internal static int ReviewNew { get; private set; }
        internal static int ReviewChanged { get; private set; }
        internal static long ReviewBytes { get; private set; }
        internal static long DownloadTotal { get; private set; }
        internal static long DownloadDone { get; private set; }
        internal static int SendingCount { get { return peers.Values.Sum(pf => pf.SendQueue.Count + (pf.Current != null ? 1 : 0)); } }
        internal static string SendingName
        {
            get
            {
                var busy = peers.Values.FirstOrDefault(pf => pf.Current != null);
                return busy != null ? busy.Current.Path : null;
            }
        }
        internal static readonly List<TeamPendingCode> Pending = new List<TeamPendingCode>();
        internal static readonly List<string> Recent = new List<string>();

        internal static event Action SyncFinished;

        /// <summary>Result of the last "Check everything matches" (null while none has run).</summary>
        internal static string CheckResult { get; private set; }
        internal static bool Checking { get; private set; }
        internal static readonly List<string> CheckFiles = new List<string>();
        internal static readonly List<string> CheckScenes = new List<string>();
        private static List<Entry> checkRemote;
        private static string[] checkDigests;
        private static bool checkRechecked;
        private static double checkAskAt = -1;

        /// <summary>Nothing of ours is mid-flight: no files queued, arriving, waiting to be written or to be saved.</summary>
        private static bool Settled
        {
            get
            {
                return peers.Values.All(pf => pf.SendQueue.Count == 0 && pf.Current == null && pf.Incoming.Count == 0) && ready.Count == 0 &&
                       touchedAssets.Count == 0 && toCheck.Count == 0 && TeamSession.Backlog == 0 && !EditorApplication.isCompiling &&
                       !EditorApplication.isUpdating;
            }
        }

        /// <summary>The last version of each file seen in this project (to spot local edits).</summary>
        private static readonly Dictionary<string, string> known = new Dictionary<string, string>();

        private static readonly Dictionary<string, string> expectWrite = new Dictionary<string, string>();
        private static readonly HashSet<string> expectDelete = new HashSet<string>();
        private static readonly HashSet<string> expectMove = new HashSet<string>();
        private static readonly HashSet<string> toCheck = new HashSet<string>();
        private static readonly List<TeamPendingCode> ready = new List<TeamPendingCode>();
        private static readonly Dictionary<string, CacheEntry> cache = new Dictionary<string, CacheEntry>();
        private static readonly HashSet<string> requested = new HashSet<string>();
        private static bool trust;
        private static bool knownReady;
        private static bool cacheLoaded;
        private static string[] remoteExcluded = new string[0];
        private static Task<List<Entry>> scan;
        private static readonly List<Action<List<Entry>>> afterScan = new List<Action<List<Entry>>>();
        private static List<Entry> remoteManifest;
        private static bool remoteManifestIsResume;
        private static List<string> reviewPaths = new List<string>();
        private static double lastChunkAt;
        private static bool needRefresh;
        private static string backupFolder;
        private static long sessionStart;

        /// <summary>The guest said yes to getting the host's project once; later catch-ups never ask again.</summary>
        private static bool accepted;

        private static double lastPeriodicSave;

        /// <summary>Files just written from a teammate; Unity re-saving them while importing is not an edit.</summary>
        private static readonly Dictionary<string, double> justWrote = new Dictionary<string, double>();

        /// <summary>Written from a teammate just now (code only arrives after the "Trust code" switch said yes).</summary>
        internal static bool JustWrote(string path)
        {
            return justWrote.ContainsKey(path);
        }

        private static readonly Dictionary<int, double> touchedAssets = new Dictionary<int, double>();
        private static double lastAutoSave;
        private static WPFMAChangeLog.Entry logEntry;
        private static double logEntryAt = -1000;

        static TeamFiles()
        {
            EditorApplication.update += Update;
            TeamSession.LinkUp += OnLinkUp;
            TeamSession.Received += OnReceived;
            TeamSession.Ended += OnEnded;
            TeamSession.Suspending += Save;
            TeamSession.PeerLeft += OnPeerLeft;
            TeamSession.Ending += () =>
            {
                RecordLiveScenes(peers.Values.ToList());
                RecordOtherGuests(TeamSession.Peers.ToList());
            };
            UnityEditor.SceneManagement.EditorSceneManager.sceneClosed += scene =>
            {
                string path = scene.path;
                if (heldScenes.ContainsKey(path))
                    EditorApplication.delayCall += () => ApplyHeldScene(path);
            };
            Restore();
        }

        internal static bool TrustCode
        {
            get { return trust; }
            set
            {
                if (trust == value)
                    return;
                trust = value;
                if (trust)
                {
                    ready.AddRange(Pending);
                    Pending.Clear();
                }
                TeamSession.Raise();
            }
        }

        /// <summary>Save changed assets (animators, menus, clips...) a moment after each edit so they sync without Ctrl+S.</summary>
        internal static bool AutoSave
        {
            get { return EditorPrefs.GetBool(AutoSaveKey, true); }
            set { EditorPrefs.SetBool(AutoSaveKey, value); }
        }

        /// <summary>Files are still coming in from the teammate (asked for, arriving, or waiting to be written).</summary>
        internal static bool Receiving
        {
            get
            {
                return requested.Count > 0 || peers.Values.Any(pf => pf.Incoming.Count > 0) || ready.Count > 0 ||
                       Phase == TeamSyncPhase.Scanning || Phase == TeamSyncPhase.Review || Phase == TeamSyncPhase.Downloading;
            }
        }

        internal static int PartialCount
        {
            get { return peers.Values.Sum(pf => pf.Incoming.Count); }
        }

        /// <summary>New files at least one teammate doesn't have yet.</summary>
        internal static int AwaitingCount
        {
            get { return AwaitingPaths.Count(); }
        }

        /// <summary>New files this teammate (or, for null, anyone) doesn't have yet.</summary>
        internal static int AwaitingCountFor(TeamPeer peer)
        {
            if (peer == null)
                return AwaitingCount;
            var pf = For(peer);
            return pf != null ? pf.Awaiting.Count : 0;
        }

        internal static IEnumerable<string> AwaitingPaths
        {
            get { return peers.Values.SelectMany(pf => pf.Awaiting.Keys).Distinct(); }
        }

        internal static bool IsAwaitingPath(string path)
        {
            return !string.IsNullOrEmpty(path) && peers.Values.Any(pf => pf.Awaiting.ContainsKey(path));
        }

        internal static bool IsAwaitingGuid(string guid)
        {
            return peers.Values.Any(pf => pf.Awaiting.Count > 0 && pf.Awaiting.ContainsValue(guid));
        }

        /// <summary>True if this asset, or anything it uses (textures, materials, meshes...), has not reached everyone yet.</summary>
        internal static string AwaitingDependency(string path)
        {
            if (string.IsNullOrEmpty(path) || !peers.Values.Any(pf => pf.Awaiting.Count > 0))
                return null;
            if (IsAwaitingPath(path))
                return path;
            foreach (var dependency in AssetDatabase.GetDependencies(path, true))
                if (IsAwaitingPath(dependency))
                    return dependency;
            return null;
        }

        private static void MarkAwaiting(PeerFiles pf, string path)
        {
            if (pf == null || string.IsNullOrEmpty(path) || Directory.Exists(path))
                return;
            string guid = AssetDatabase.AssetPathToGUID(path);
            if (string.IsNullOrEmpty(guid))
                return;
            pf.Awaiting[path] = guid;
            pf.AwaitingSince[path] = TeamSession.Now;
        }

        private static void ClearAwaiting(PeerFiles pf, string path)
        {
            if (pf != null && pf.Awaiting.Remove(path))
            {
                pf.AwaitingSince.Remove(path);
                TeamSession.Raise();
            }
        }

        private static void ClearAwaitingEverywhere(string path)
        {
            foreach (var pf in peers.Values)
                ClearAwaiting(pf, path);
        }

        /// <summary>Tells a teammate these files are in this project now (or were deliberately not taken).</summary>
        private static void Confirm(PeerFiles pf, IEnumerable<string> paths)
        {
            if (pf == null)
                return;
            var list = paths.Where(p => !string.IsNullOrEmpty(p)).Distinct().ToArray();
            for (int i = 0; i < list.Length; i += 400)
                SendTo(pf, new TeamMessage { t = "fhave", a = list.Skip(i).Take(400).ToArray() });
        }

        /// <summary>Chosen in the setup window: scripts from the teammate are added straight away.</summary>
        internal static bool TrustOnConnect
        {
            get { return EditorPrefs.GetBool("WPFMA.Team.TrustScripts." + ProjectKey, false); }
            set { EditorPrefs.SetBool("WPFMA.Team.TrustScripts." + ProjectKey, value); }
        }

        /// <summary>Chosen in the setup window: the guest gets the host's project without being asked.</summary>
        internal static bool AutoGetProject
        {
            get { return EditorPrefs.GetBool("WPFMA.Team.AutoGet", true); }
            set { EditorPrefs.SetBool("WPFMA.Team.AutoGet", value); }
        }

        private static double autoCheckAt = -1;
        private static bool autoCheck;

        internal static bool Active
        {
            get { return TeamSession.IsLinked && Phase == TeamSyncPhase.Live; }
        }

        // ---- What is shared ---------------------------------------------------------------------------------------

        internal 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>Folders this project never sends (the host's list applies to both sides).</summary>
        internal static List<string> Excluded
        {
            get
            {
                string stored = EditorPrefs.GetString("WPFMA.Team.Exclude." + ProjectKey, null);
                if (stored == null)
                    return DetectLicensed();
                return stored.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            }
            set
            {
                EditorPrefs.SetString("WPFMA.Team.Exclude." + ProjectKey, string.Join("\n", (value ?? new List<string>()).ToArray()));
                ForgetExcluded();
            }
        }

        internal static bool ShareConfirmed
        {
            get { return EditorPrefs.GetBool("WPFMA.Team.ShareOk." + ProjectKey, false); }
            set { EditorPrefs.SetBool("WPFMA.Team.ShareOk." + ProjectKey, value); }
        }

        internal static string[] RemoteExcluded
        {
            get { return remoteExcluded; }
        }

        /// <summary>Top-level folders of Assets, for the share settings list.</summary>
        internal static List<string> TopFolders()
        {
            return Directory.GetDirectories("Assets")
                .Select(d => d.Replace('\\', '/'))
                .Where(d => !AlwaysSkipped.Contains(d) && !Path.GetFileName(d).StartsWith(".") && !d.EndsWith("~"))
                .OrderBy(d => d, StringComparer.OrdinalIgnoreCase)
                .ToList();
        }

        /// <summary>
        /// Folders that look like paid content that is licensed per buyer. Only a starting point: the host reviews
        /// the list before sharing.
        /// </summary>
        internal static List<string> DetectLicensed()
        {
            var found = new List<string>();
            try
            {
                foreach (var folder in TopFolders())
                {
                    string name = Path.GetFileName(folder).ToLowerInvariant();
                    if (name.Contains("Bobs Burger") &&
                        Directory.EnumerateFiles(folder, "*.shader", SearchOption.AllDirectories).Any(f => Path.GetFileName(f).IndexOf("Sussy", StringComparison.Ordinal) >= 0 ||
                                                                                                         f.Replace('\\', '/').Contains("/Pro/")))
                        found.Add(folder);
                }
            }
            catch (Exception)
            {
            }
            return found;
        }

        private static string[] excludedCache;
        private static double excludedAt = -10;

        /// <summary>
        /// Folders never synced. The host uses its own share list; the guest uses the host's list plus whatever looks
        /// like paid content in its own project. Cached for a few seconds: this is checked for every file.
        /// </summary>
        private static string[] ExcludedNow()
        {
            if (excludedCache != null && TeamSession.Now - excludedAt < 5.0)
                return excludedCache;
            var own = TeamSession.IsHost || TeamSession.State == TeamState.Idle ? Excluded : DetectLicensed();
            excludedCache = own.Concat(remoteExcluded).Concat(AlwaysSkipped).Distinct().ToArray();
            excludedAt = TeamSession.Now;
            return excludedCache;
        }

        private static void ForgetExcluded()
        {
            excludedCache = null;
        }

        internal static bool Shared(string path)
        {
            return Shared(path, ExcludedNow());
        }

        private static bool Shared(string path, string[] excluded)
        {
            if (string.IsNullOrEmpty(path) || !path.StartsWith("Assets/", StringComparison.Ordinal) || path.Contains(".."))
                return false;
            foreach (var folder in excluded)
                if (path == folder || path.StartsWith(folder + "/", StringComparison.Ordinal))
                    return false;

            string file = Path.GetFileName(path);
            if (file.StartsWith(".") || file.EndsWith("~") || path.Contains("~/") || path.Contains("/."))
                return false;

            string ext = Path.GetExtension(path).ToLowerInvariant();
            return ext != ".meta" && ext != ".unitypackage" && ext != ".tmp";
        }

        internal static bool IsCode(string path)
        {
            return CodeExtensions.Contains(Path.GetExtension(path).ToLowerInvariant());
        }

        // ---- Session events ---------------------------------------------------------------------------------------

        private static void OnLinkUp(bool resumed)
        {
            var pf = For(TeamSession.Sender);
            if (pf == null)
                return;
            if (resumed && pf.Awaiting.Count > 0)
                SendTo(pf, new TeamMessage { t = "fask", a = pf.Awaiting.Keys.ToArray() });

            if (!resumed || sessionStart == 0)
                sessionStart = DateTime.UtcNow.Ticks;

            bool firstHere = !TeamSession.IsHost || !TeamSession.Peers.Any(p => p.Link != null && p.Id != pf.Id);
            if (!resumed)
            {
                if (firstHere)
                    trust = TrustOnConnect;
                if (!TeamSession.IsHost && AutoGetProject)
                    accepted = true;
            }
            else if (!TeamSession.IsHost && Phase == TeamSyncPhase.Live)
            {
                // After any reconnect, quietly make sure everything still matches the host.
                autoCheckAt = TeamSession.Now + 8.0;
            }

            if (TeamSession.IsHost)
                SendTo(pf, new TeamMessage { t = "rules", a = Excluded.ToArray() });

            if (resumed && Phase == TeamSyncPhase.Live)
            {
                PhaseText = "Checking files after the reload...";
                StartScan(list =>
                {
                    SendTo(pf, new TeamMessage { t = "man", on = true }, Encoding.UTF8.GetBytes(WriteManifest(list)));
                    TryDiff();
                });
                return;
            }

            if (TeamSession.IsHost)
            {
                if (Phase != TeamSyncPhase.Live)
                    SetPhase(TeamSyncPhase.Live, null);
                // A new guest takes the host's project, so what they will have is what the host has now.
                if (!resumed && pf.Agreed.Count > 0)
                {
                    // We've worked with them before: wait for their file list and compare (see WPFMATeamReunion).
                    HostAwaitReunion(pf);
                    StartScan(null);
                }
                else if (!resumed)
                    StartScan(list =>
                    {
                        pf.Agreed.Clear();
                        foreach (var entry in list)
                            pf.Agreed[entry.Path] = entry.Hash;
                    });
                else
                    StartScan(null);
            }
            else if (!resumed && pf.Agreed.Count > 0)
                GuestStartReunion(pf);
            else
            {
                SetPhase(TeamSyncPhase.Scanning, "Asking " + TeamSession.RemoteName + " for the project's file list...");
                SendTo(pf, new TeamMessage { t = "manreq" });
            }
        }

        /// <summary>Host: a guest left; forget what was in flight with them (the others carry on).</summary>
        private static void OnPeerLeft()
        {
            var peer = TeamSession.Sender;
            // Another guest left while we stay: remember what we both had, for working apart with them later.
            if (!TeamSession.IsHost && peer != null && !peer.IsHost)
                RecordOtherGuests(new List<TeamPeer> { peer });
            PeerFiles pf;
            if (peer == null || !peers.TryGetValue(peer.Id, out pf))
                return;
            foreach (var item in pf.Incoming.Values)
            {
                CloseQuietly(item.Stream);
                DeleteQuietly(item.Temp);
            }
            if (pf.Current != null)
            {
                CloseQuietly(pf.Current.Stream);
                pf.Current.Md5.Dispose();
            }
            RecordLiveScenes(new List<PeerFiles> { pf });
            CaptureBases(pf, true);
            SaveAgreed(pf);
            if (pf == reunionPeer)
                ResetReunion();
            ForgetTheirFiles(peer.Id);
            peers.Remove(peer.Id);
            TeamSession.Raise();
        }

        private static void OnEnded()
        {
            ResetReunion();
            ForgetTheirFiles(null);
            foreach (var pf in peers.Values)
            {
                // What we last had together is kept, so working apart and reconnecting later merges instead of
                // starting over (see WPFMATeamReunion).
                CaptureBases(pf, true);
                if (!pf.Reuniting)
                    SaveAgreed(pf);
                foreach (var item in pf.Incoming.Values)
                    CloseQuietly(item.Stream);
                if (pf.Current != null)
                    CloseQuietly(pf.Current.Stream);
            }
            peers.Clear();
            foreach (var item in Pending)
                DeleteQuietly(item.Temp);
            Pending.Clear();
            touchedAssets.Clear();
            logEntry = null;
            ready.Clear();
            requested.Clear();
            trust = false;
            remoteExcluded = new string[0];
            remoteManifest = null;
            knownReady = false;
            known.Clear();
            // The session's own file map goes; the per-teammate "agreed-" records stay (they used to be deleted here,
            // which made every reconnect after a session ended a first session where the host's project won).
            DeleteQuietly(StatePath);
            sessionStart = 0;
            accepted = false;
            justWrote.Clear();
            foreach (var held in heldScenes.Values)
                DeleteQuietly(held.Temp);
            heldScenes.Clear();
            ForgetExcluded();
            Checking = false;
            CheckResult = null;
            CheckFiles.Clear();
            CheckScenes.Clear();
            autoCheckAt = -1;
            autoCheck = false;
            SetPhase(TeamSyncPhase.Off, null);
            SessionState.EraseString(SavedKey);
        }

        private static void Save()
        {
            var saved = new TeamFilesSaved
            {
                live = Phase == TeamSyncPhase.Live,
                trust = trust,
                since = sessionStart,
                accepted = accepted,
                remoteExcluded = remoteExcluded,
                pendingPath = Pending.Select(p => p.Path).ToArray(),
                pendingTemp = Pending.Select(p => p.Temp).ToArray(),
                pendingMeta = Pending.Select(p => p.Meta ?? string.Empty).ToArray(),
                pendingHash = Pending.Select(p => p.Hash).ToArray(),
                pendingMtime = Pending.Select(p => p.Mtime).ToArray(),
                pendingSize = Pending.Select(p => p.Size).ToArray(),
                pendingFrom = Pending.Select(p => p.From ?? string.Empty).ToArray()
            };
            var list = new List<TeamPeerFilesSaved>();
            foreach (var pf in peers.Values)
            {
                var parts = pf.Incoming.Values.ToList();
                foreach (var item in parts)
                    CloseQuietly(item.Stream);
                list.Add(new TeamPeerFilesSaved
                {
                    id = pf.Id,
                    awaiting = pf.Awaiting.Keys.ToArray(),
                    inPath = parts.Select(i => i.Path).ToArray(),
                    inTemp = parts.Select(i => i.Temp).ToArray(),
                    inMeta = parts.Select(i => i.Meta ?? string.Empty).ToArray(),
                    inMtime = parts.Select(i => i.Mtime).ToArray(),
                    inNext = parts.Select(i => i.Next).ToArray(),
                    inBase = parts.Select(i => i.Base ?? string.Empty).ToArray()
                });
                foreach (var item in parts)
                    item.Stream = OpenAppend(item.Temp);
            }
            saved.peers = list.ToArray();
            SessionState.SetString(SavedKey, JsonUtility.ToJson(saved));
            SaveCache();
            SaveState();
        }

        private static string StatePath
        {
            get { return Path.Combine("Library", "WPFMATeam", "state.txt"); }
        }

        /// <summary>Keeps the version maps on disk so reloads and restarts know what was already shared.</summary>
        private static void SaveState()
        {
            if (!knownReady)
                return;
            try
            {
                Directory.CreateDirectory(Path.GetDirectoryName(StatePath));
                File.WriteAllLines(StatePath, known.Select(pair => pair.Key + "\t" + pair.Value).ToArray());
                foreach (var pf in peers.Values)
                    SaveAgreed(pf);
            }
            catch (Exception)
            {
            }
        }

        private static string AgreedPath(PeerFiles pf)
        {
            return Path.Combine("Library", "WPFMATeam", "agreed-" + WPFMAPaths.SafeFileName(pf.Id) + ".txt");
        }

        private static void SaveAgreed(PeerFiles pf)
        {
            if (!knownReady)
                return;
            try
            {
                Directory.CreateDirectory(Path.GetDirectoryName(StatePath));
                File.WriteAllLines(AgreedPath(pf), pf.Agreed.Select(pair => pair.Key + "\t" + pair.Value).ToArray());
                if (!pf.Reuniting)
                    CaptureBases(pf, false);
            }
            catch (Exception)
            {
            }
        }

        private static void LoadAgreed(PeerFiles pf)
        {
            if (pf.AgreedLoaded)
                return;
            pf.AgreedLoaded = true;
            try
            {
                string file = AgreedPath(pf);
                if (!File.Exists(file))
                    return;
                foreach (var line in File.ReadAllLines(file))
                {
                    int tab = line.IndexOf('\t');
                    if (tab > 0 && !pf.Agreed.ContainsKey(line.Substring(0, tab)))
                        pf.Agreed[line.Substring(0, tab)] = line.Substring(tab + 1);
                }
            }
            catch (Exception)
            {
            }
        }

        private static void LoadState()
        {
            try
            {
                if (!File.Exists(StatePath))
                    return;
                foreach (var line in File.ReadAllLines(StatePath))
                {
                    var parts = line.Split('\t');
                    if (parts.Length >= 2 && parts[1].Length > 0)
                        known[parts[0]] = parts[1];
                }
                knownReady = known.Count > 0;
            }
            catch (Exception)
            {
            }
        }

        private static void Restore()
        {
            string json = SessionState.GetString(SavedKey, string.Empty);
            if (string.IsNullOrEmpty(json))
                return;
            SessionState.EraseString(SavedKey);
            RestoreFrom(json);
        }

        /// <summary>Puts back the file sync state saved before Unity closed, when rejoining a session.</summary>
        internal static void RestoreFrom(string json)
        {
            try
            {
                var saved = JsonUtility.FromJson<TeamFilesSaved>(json);
                Phase = saved.live ? TeamSyncPhase.Live : TeamSyncPhase.Off;
                if (saved.live)
                    LoadState();
                trust = saved.trust;
                sessionStart = saved.since;
                accepted = saved.accepted;
                foreach (var peerSaved in saved.peers ?? new TeamPeerFilesSaved[0])
                {
                    var pf = For(peerSaved.id);
                    if (pf == null)
                        continue;
                    for (int i = 0; peerSaved.inPath != null && i < peerSaved.inPath.Length; i++)
                    {
                        if (!File.Exists(peerSaved.inTemp[i]))
                            continue;
                        // Keep only whole pieces; a piece cut short by the reload is fetched again.
                        long whole = (long)peerSaved.inNext[i] * ChunkSize;
                        if (new FileInfo(peerSaved.inTemp[i]).Length < whole)
                            continue;
                        using (var trim = new FileStream(peerSaved.inTemp[i], FileMode.Open, FileAccess.Write))
                            trim.SetLength(whole);
                        pf.Incoming[peerSaved.inPath[i]] = new Incoming
                        {
                            Path = peerSaved.inPath[i],
                            Temp = peerSaved.inTemp[i],
                            Meta = string.IsNullOrEmpty(peerSaved.inMeta[i]) ? null : peerSaved.inMeta[i],
                            Mtime = peerSaved.inMtime[i],
                            Next = peerSaved.inNext[i],
                            Base = string.IsNullOrEmpty(peerSaved.inBase[i]) ? null : peerSaved.inBase[i],
                            Stream = OpenAppend(peerSaved.inTemp[i])
                        };
                    }
                    foreach (var path in peerSaved.awaiting ?? new string[0])
                        MarkAwaiting(pf, path);
                }
                remoteExcluded = saved.remoteExcluded ?? new string[0];
                for (int i = 0; saved.pendingPath != null && i < saved.pendingPath.Length; i++)
                {
                    if (!File.Exists(saved.pendingTemp[i]))
                        continue;
                    Pending.Add(new TeamPendingCode
                    {
                        Path = saved.pendingPath[i],
                        Temp = saved.pendingTemp[i],
                        Meta = string.IsNullOrEmpty(saved.pendingMeta[i]) ? null : saved.pendingMeta[i],
                        Hash = saved.pendingHash[i],
                        Mtime = saved.pendingMtime[i],
                        Size = saved.pendingSize[i],
                        From = saved.pendingFrom != null && i < saved.pendingFrom.Length ? saved.pendingFrom[i] : null
                    });
                }
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA Team] Could not restore file sync state: " + e.Message);
            }
        }

        private static void SetPhase(TeamSyncPhase phase, string text)
        {
            Phase = phase;
            PhaseText = text;
            TeamSession.Raise();
        }

        // ---- Messages ---------------------------------------------------------------------------------------------

        private static void OnReceived(TeamMessage message, byte[] blob)
        {
            var pf = For(TeamSession.Sender);
            if (OnReunionMessage(pf, message, blob) || OnTheirFilesMessage(pf, message, blob))
                return;
            switch (message.t)
            {
                case "rules":
                    if (!TeamSession.IsHost)
                        remoteExcluded = (message.a ?? new string[0]).Where(f => f.StartsWith("Assets/", StringComparison.Ordinal)).ToArray();
                    ForgetExcluded();
                    break;

                case "manreq":
                    StartScan(list =>
                    {
                        // They have no record of working with us: the normal first-time sync, our project is the reference.
                        if (TeamSession.IsHost && pf != null && pf.Reuniting)
                        {
                            pf.Reuniting = false;
                            pf.Agreed.Clear();
                            foreach (var entry in list)
                                pf.Agreed[entry.Path] = entry.Hash;
                        }
                        SendTo(pf, new TeamMessage { t = "man", on = false }, Encoding.UTF8.GetBytes(WriteManifest(list)));
                    });
                    break;

                case "man":
                    remoteManifest = ReadManifest(blob != null ? Encoding.UTF8.GetString(blob) : string.Empty);
                    remoteManifestIsResume = message.on;
                    if (!message.on)
                        SetPhase(TeamSyncPhase.Scanning, "Comparing with your project...");
                    if (scan == null)
                        StartScan(list => TryDiff());
                    break;

                case "get":
                    if (pf == null)
                        break;
                    var paths = message.a ?? new string[0];
                    for (int i = 0; i < paths.Length; i++)
                    {
                        string path = paths[i];
                        int start;
                        if (message.b != null && i < message.b.Length && int.TryParse(message.b[i], out start) && start > 0)
                            pf.StartChunk[path] = start;
                        if (Shared(path) && (File.Exists(path) || Directory.Exists(path)))
                            Enqueue(pf, path);
                        else
                            SendTo(pf, new TeamMessage { t = "fmiss", f = path });
                    }
                    break;

                case "vreq":
                    // The host asked the guest to check; the guest compares against the host and reports back.
                    if (!TeamSession.IsHost)
                        StartCheck();
                    break;

                case "vman":
                    if (pf != null)
                        pf.CheckAnswerAt = TeamSession.Now;
                    break;

                case "vmanr":
                    checkRemote = ReadManifest(blob != null ? Encoding.UTF8.GetString(blob) : string.Empty);
                    checkDigests = message.a ?? new string[0];
                    StartScan(list => FinishCheck(list));
                    break;

                case "vres":
                    if (TeamSession.IsHost && pf != null)
                    {
                        pf.CheckResult = message.m;
                        CombineCheckResults();
                        TeamSession.Raise();
                    }
                    break;

                case "fask":
                    Confirm(pf, (message.a ?? new string[0]).Where(File.Exists));
                    break;

                case "fhave":
                    foreach (var path in message.a ?? new string[0])
                        ClearAwaiting(pf, path);
                    break;

                case "fmiss":
                    if (requested.Remove(message.f))
                        CheckDownloadDone();
                    break;

                case "fput":
                    if (pf != null)
                        ReceiveChunk(pf, message, blob);
                    break;

                case "fdir":
                    if (pf != null)
                        ReceiveFolder(pf, message);
                    break;

                case "fdel":
                    if (pf != null)
                        ReceiveDelete(pf, message.f);
                    break;

                case "fmove":
                    if (pf != null)
                        ReceiveMove(pf, message.f, message.m);
                    break;

            }
        }

        // ---- File lists -------------------------------------------------------------------------------------------

        private static void StartScan(Action<List<Entry>> done)
        {
            // Several teammates can ask at once: everyone waiting gets the next finished scan.
            afterScan.Add(done);
            if (scan != null)
                return;
            TeamStandIns.RepairFiles();
            LoadCache();
            var excluded = ExcludedNow();
            Dictionary<string, CacheEntry> snapshot;
            lock (cache)
                snapshot = new Dictionary<string, CacheEntry>(cache);
            scan = Task.Run(() => Scan(excluded, snapshot));
        }

        private static List<Entry> Scan(string[] excluded, Dictionary<string, CacheEntry> snapshot)
        {
            var list = new List<Entry>();
            var stack = new Stack<string>();
            stack.Push("Assets");

            while (stack.Count > 0)
            {
                string folder = stack.Pop();
                string[] dirs, files;
                try
                {
                    dirs = Directory.GetDirectories(folder);
                    files = Directory.GetFiles(folder);
                }
                catch (Exception)
                {
                    continue;
                }

                foreach (var raw in dirs)
                {
                    string dir = raw.Replace('\\', '/');
                    if (!Shared(dir, excluded))
                        continue;
                    stack.Push(dir);
                    list.Add(new Entry { Path = dir, Dir = true, Hash = "dir:" + HashOf(dir + ".meta"), Mtime = MtimeOf(dir + ".meta") });
                }

                foreach (var raw in files)
                {
                    string file = raw.Replace('\\', '/');
                    if (!Shared(file, excluded))
                        continue;

                    try
                    {
                        var info = new FileInfo(file);
                        long mtime = Math.Max(info.LastWriteTimeUtc.Ticks, MtimeOf(file + ".meta"));
                        CacheEntry cached;
                        string hash;
                        if (snapshot.TryGetValue(file, out cached) && cached.Size == info.Length && cached.Mtime == mtime)
                            hash = cached.Hash;
                        else
                        {
                            hash = HashOf(file) + ":" + HashOf(file + ".meta");
                            lock (cache)
                                cache[file] = new CacheEntry { Size = info.Length, Mtime = mtime, Hash = hash };
                        }

                        list.Add(new Entry { Path = file, Hash = hash, Size = info.Length, Mtime = mtime });
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            return list;
        }

        private static string WriteManifest(List<Entry> list)
        {
            var text = new StringBuilder();
            foreach (var e in list)
                text.Append(e.Path).Append('\t').Append(e.Hash).Append('\t').Append(e.Size).Append('\t').Append(e.Mtime).Append('\t').Append(e.Dir ? '1' : '0').Append('\n');
            return text.ToString();
        }

        private static List<Entry> ReadManifest(string text)
        {
            var list = new List<Entry>();
            foreach (var line in text.Split('\n'))
            {
                var parts = line.Split('\t');
                if (parts.Length < 5)
                    continue;
                long size, mtime;
                long.TryParse(parts[2], out size);
                long.TryParse(parts[3], out mtime);
                list.Add(new Entry { Path = parts[0], Hash = parts[1], Size = size, Mtime = mtime, Dir = parts[4] == "1" });
            }
            return list;
        }

        private static List<Entry> lastScan;

        private static void TryDiff()
        {
            if (remoteManifest == null || lastScan == null || scan != null)
                return;

            // The host's project is the reference. After a reload each side pushes what it changed itself, so the
            // host never pulls the guest's versions of files (that would bring the guest's own copies of packages in).
            if (remoteManifestIsResume && TeamSession.IsHost)
            {
                remoteManifest = null;
                PhaseText = null;
                TeamSession.Raise();
                return;
            }
            var remoteList = remoteManifest;
            var hostFiles = For(TeamSession.HostPeer);
            var agreed = hostFiles != null ? hostFiles.Agreed : new Dictionary<string, string>();

            var local = lastScan.ToDictionary(e => e.Path, e => e);
            var need = new List<Entry>();
            int added = 0, changed = 0;
            long bytes = 0;

            foreach (var entry in remoteManifest)
            {
                if (!Shared(entry.Path) || TeamScene.IsLive(entry.Path))
                    continue;

                Entry mine;
                bool have = local.TryGetValue(entry.Path, out mine);
                if (have && mine.Hash == entry.Hash)
                    continue;
                if (have && entry.Dir)
                    continue;
                if (remoteManifestIsResume)
                {
                    string both;
                    bool hasAgreed = agreed.TryGetValue(entry.Path, out both);
                    // They still have the version we both had: any change is ours and goes out on its own.
                    if (hasAgreed && both == entry.Hash)
                        continue;
                    // We deleted it while apart: our delete goes out instead.
                    if (!have && hasAgreed)
                        continue;
                }

                need.Add(entry);
                bytes += entry.Size;
                if (have)
                    changed++;
                else
                    added++;
            }

            bool resume = remoteManifestIsResume;
            remoteManifest = null;

            if (!resume)
            {
                foreach (var entry in lastScan)
                    agreed[entry.Path] = entry.Hash;
                foreach (var entry in remoteList)
                    agreed[entry.Path] = entry.Hash;
            }

            if (resume)
            {
                if (need.Count > 0)
                {
                    Request(need.Select(e => e.Path).ToList(), bytes);
                    AddRecent("Catching up on " + need.Count + " file(s) changed during the reload");
                }
                PhaseText = null;
                TeamSession.Raise();
                return;
            }

            if (need.Count == 0)
            {
                FinishInitial();
                return;
            }

            reviewPaths = need.Select(e => e.Path).ToList();
            ReviewNew = added;
            ReviewChanged = changed;
            ReviewBytes = bytes;
            SetPhase(TeamSyncPhase.Review, null);
            if (accepted)
                StartDownload();
        }

        /// <summary>Guest accepted the review: download everything that differs.</summary>
        internal static void StartDownload()
        {
            if (Phase != TeamSyncPhase.Review)
                return;
            accepted = true;
            Request(reviewPaths, ReviewBytes);
            SetPhase(TeamSyncPhase.Downloading, "Downloading " + reviewPaths.Count + " file(s) from " + TeamSession.RemoteName + "...");
            reviewPaths = new List<string>();
        }

        private static void Request(List<string> paths, long bytes)
        {
            var pf = For(TeamSession.HostPeer);
            if (pf == null)
                return;
            DownloadTotal = bytes;
            DownloadDone = 0;
            foreach (var path in paths)
            {
                requested.Add(path);
                Incoming part;
                if (pf.Incoming.TryGetValue(path, out part))
                    DownloadDone += (long)part.Next * ChunkSize;
            }
            // Files partly received before a reload continue from where they stopped.
            var from = paths.Select(p => pf.Incoming.ContainsKey(p) ? pf.Incoming[p].Next.ToString(CultureInfo.InvariantCulture) : "0").ToList();
            for (int i = 0; i < paths.Count; i += 400)
                SendTo(pf, new TeamMessage { t = "get", a = paths.Skip(i).Take(400).ToArray(), b = from.Skip(i).Take(400).ToArray() });
        }

        private static void CheckDownloadDone()
        {
            if (Phase == TeamSyncPhase.Downloading && requested.Count == 0 && PartialCount == 0 && ready.Count == 0)
                FinishInitial();
        }

        private static void FinishInitial()
        {
            SetPhase(TeamSyncPhase.Live, null);
            GuestReunionFinished();
            if (!TeamSession.IsHost)
                autoCheckAt = TeamSession.Now + 5.0;
            AddRecent("Project files are in sync with " + TeamSession.RemoteName);
            if (Pending.Count > 0)
                TeamSession.AddSystem(Pending.Count + " script file(s) are waiting for you to trust them (see Files).");
            if (SyncFinished != null)
                SyncFinished();
        }

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

        /// <summary>Compares everything with the host's project: files (content and asset IDs) and the shared scenes.</summary>
        internal static void StartCheck()
        {
            if (!TeamSession.IsLinked || Checking)
                return;
            Checking = true;
            checkRechecked = false;
            CheckResult = null;
            CheckFiles.Clear();
            CheckScenes.Clear();
            if (TeamSession.IsHost)
            {
                foreach (var pf in Linked)
                    pf.CheckResult = null;
                TeamSession.Send(new TeamMessage { t = "vreq" });
            }
            else
                checkAskAt = TeamSession.Now;
            TeamSession.Raise();
        }

        /// <summary>Host: one line for everyone's answers once they are all in.</summary>
        private static void CombineCheckResults()
        {
            var linked = Linked;
            if (linked.Count == 0 || linked.Any(pf => pf.CheckResult == null))
                return;
            Checking = false;
            if (linked.Count == 1)
                CheckResult = linked[0].CheckResult;
            else if (linked.All(pf => pf.CheckResult.StartsWith("Everything matches", StringComparison.Ordinal)))
                CheckResult = "Everything matches for " + string.Join(" and ", linked.Select(pf => pf.Name).ToArray()) + ".";
            else
                CheckResult = string.Join("  ", linked.Select(pf => pf.Name + ": " + pf.CheckResult).ToArray());
        }

        /// <summary>Both sides wait (up to 10 seconds) until nothing is mid-transfer before comparing.</summary>
        private static void PumpCheck()
        {
            if (autoCheckAt >= 0 && TeamSession.Now >= autoCheckAt && !Checking && Phase == TeamSyncPhase.Live)
            {
                autoCheckAt = -1;
                autoCheck = true;
                StartCheck();
            }
            if (checkAskAt >= 0 && TeamSession.Now >= checkAskAt && (Settled || TeamSession.Now - checkAskAt > 10))
            {
                checkAskAt = -1;
                SendTo(For(TeamSession.HostPeer), new TeamMessage { t = "vman" });
            }
            foreach (var pf in peers.Values.ToList())
            {
                if (pf.CheckAnswerAt < 0 || !(Settled || TeamSession.Now - pf.CheckAnswerAt > 10))
                    continue;
                pf.CheckAnswerAt = -1;
                var asker = pf;
                StartScan(list => SendTo(asker, new TeamMessage
                {
                    t = "vmanr",
                    a = TeamScene.LiveScenes.Select(s => s + "|" + (TeamScene.DigestOf(s) ?? string.Empty)).ToArray()
                }, Encoding.UTF8.GetBytes(WriteManifest(list))));
            }
        }

        private static string Content(string hash)
        {
            // Compare the file itself and its asset ID, not the rest of the .meta, which Unity may re-save.
            int colon = (hash ?? string.Empty).IndexOf(':');
            return colon < 0 ? hash : hash.Substring(0, colon);
        }

        private static void FinishCheck(List<Entry> local)
        {
            var mine = local.ToDictionary(e => e.Path, e => e);
            var pending = new HashSet<string>(Pending.Select(p => p.Path));
            int same = 0, waiting = 0;
            foreach (var entry in checkRemote ?? new List<Entry>())
            {
                if (entry.Dir || !Shared(entry.Path) || entry.Path.EndsWith(".unity", StringComparison.OrdinalIgnoreCase) && TeamScene.IsLive(entry.Path))
                    continue;
                if (pending.Contains(entry.Path))
                {
                    waiting++;
                    continue;
                }
                Entry have;
                if (mine.TryGetValue(entry.Path, out have) && Content(have.Hash) == Content(entry.Hash) &&
                    GuidOf(entry.Path) != null)
                    same++;
                else
                    CheckFiles.Add(entry.Path);
            }

            foreach (var pair in checkDigests ?? new string[0])
            {
                int bar = pair.LastIndexOf('|');
                if (bar <= 0)
                    continue;
                string path = pair.Substring(0, bar);
                string digest = pair.Substring(bar + 1);
                if (!string.IsNullOrEmpty(digest) && TeamScene.DigestOf(path) != digest)
                    CheckScenes.Add(path);
            }

            var text = new StringBuilder();
            if (CheckFiles.Count == 0 && CheckScenes.Count == 0)
                text.Append("Everything matches: " + same + " file(s)" + (checkDigests != null && checkDigests.Length > 0 ? " and the shared scene" : string.Empty) + ".");
            else
            {
                if (CheckFiles.Count > 0)
                    text.Append(CheckFiles.Count + " file(s) differ from the host's. ");
                if (CheckScenes.Count > 0)
                    text.Append("The shared scene differs from the host's. ");
                text.Append(same + " file(s) match.");
            }
            if (waiting > 0)
                text.Append(" " + waiting + " script(s) are waiting for trust.");

            if ((CheckFiles.Count > 0 || CheckScenes.Count > 0) && !checkRechecked)
            {
                // Something may still have been on its way: look once more in a few seconds before reporting.
                checkRechecked = true;
                CheckFiles.Clear();
                CheckScenes.Clear();
                checkAskAt = TeamSession.Now + 3.0;
                return;
            }

            Checking = false;
            CheckResult = text.ToString();
            SendTo(For(TeamSession.HostPeer), new TeamMessage { t = "vres", m = CheckResult });
            if (autoCheck)
            {
                autoCheck = false;
                if (CheckFiles.Count > 0 || CheckScenes.Count > 0)
                {
                    TeamSession.AddSystem("Found " + (CheckFiles.Count > 0 ? CheckFiles.Count + " file(s)" : "the scene") +
                                          " not matching the host's, so they're being matched again.");
                    FixDifferences();
                }
                else
                    CheckResult = null;
            }
            TeamSession.Raise();
        }

        private static string GuidOf(string path)
        {
            string guid = AssetDatabase.AssetPathToGUID(path);
            return string.IsNullOrEmpty(guid) ? null : guid;
        }

        /// <summary>Guest: get the host's versions of everything the check found different.</summary>
        internal static void FixDifferences()
        {
            if (TeamSession.IsHost)
                return;
            if (CheckFiles.Count > 0)
            {
                Request(CheckFiles.ToList(), 0);
                AddRecent("Getting the host's version of " + CheckFiles.Count + " file(s)");
            }
            foreach (var scene in CheckScenes)
                TeamScene.RequestScene(scene);
            CheckFiles.Clear();
            CheckScenes.Clear();
            CheckResult = "Getting the host's versions...";
            TeamSession.Raise();
        }

        /// <summary>Queues a file for one teammate.</summary>
        private static void Enqueue(PeerFiles pf, string path, bool forced = false)
        {
            if (pf == null)
                return;
            if (forced)
                pf.ForcedSends.Add(path);
            if (pf.Current != null && pf.Current.Path == path)
            {
                CloseQuietly(pf.Current.Stream);
                pf.Current = null;
            }
            if (!pf.SendQueue.Contains(path))
                pf.SendQueue.Add(path);
        }

        /// <summary>Queues a file for everyone (or everyone but the teammate it came from).</summary>
        private static void EnqueueAll(string path, PeerFiles except = null)
        {
            foreach (var pf in Linked)
            {
                if (pf == except || pf.Reuniting)
                    continue;
                if (!pf.BaseOf.ContainsKey(path))
                    pf.BaseOf[path] = pf.Agreed.ContainsKey(path) ? pf.Agreed[path] : string.Empty;
                Enqueue(pf, path);
            }
        }

        private static void PumpSend()
        {
            foreach (var pf in Linked)
            {
                var peer = pf.Peer;
                if (peer == null || peer.Link == null || !peer.Up)
                    continue;
                int guard = 0;
                while (peer.Backlog < BacklogLimit && guard++ < 64)
                {
                    if (pf.Current == null)
                    {
                        if (pf.SendQueue.Count == 0)
                            break;
                        string path = pf.SendQueue[0];
                        pf.SendQueue.RemoveAt(0);
                        OpenNext(pf, path);
                        continue;
                    }

                    var current = pf.Current;
                    var buffer = new byte[ChunkSize];
                    int read = 0;
                    try
                    {
                        read = current.Stream.Read(buffer, 0, buffer.Length);
                    }
                    catch (Exception)
                    {
                    }

                    bool last = current.Stream.Position >= current.Stream.Length || read <= 0;
                    var chunk = new byte[Math.Max(0, read)];
                    System.Buffer.BlockCopy(buffer, 0, chunk, 0, chunk.Length);

                    string hash = null;
                    if (last)
                    {
                        current.Md5.TransformFinalBlock(chunk, 0, chunk.Length);
                        hash = Hex(current.Md5.Hash) + ":" + current.MetaHash;
                    }
                    else
                    {
                        current.Md5.TransformBlock(chunk, 0, chunk.Length, null, 0);
                    }

                    SendTo(pf, new TeamMessage
                    {
                        t = "fput",
                        f = current.Path,
                        n = current.Index,
                        on = last,
                        h = hash,
                        d = current.Index == 0 ? current.Meta : null,
                        mt = current.Mtime.ToString(CultureInfo.InvariantCulture),
                        o = current.Forced,
                        s = current.Index == 0 ? current.Base : null
                    }, chunk);
                    current.Index++;

                    if (last)
                    {
                        pf.BaseOf.Remove(current.Path);
                        known[current.Path] = hash;
                        pf.Agreed[current.Path] = hash;
                        CloseQuietly(current.Stream);
                        current.Md5.Dispose();
                        pf.Current = null;
                    }
                }
            }
        }

        private static void OpenNext(PeerFiles pf, string path)
        {
            // A file Unity has not imported yet has no .meta (asset ID); import it first so the ID travels with it.
            if (File.Exists(path) && !File.Exists(path + ".meta"))
                AssetDatabase.ImportAsset(path);
            string meta = File.Exists(path + ".meta") ? File.ReadAllText(path + ".meta") : null;

            if (Directory.Exists(path))
            {
                SendTo(pf, new TeamMessage { t = "fdir", f = path, d = meta });
                known[path] = "dir:" + HashOf(path + ".meta");
                pf.Agreed[path] = known[path];
                return;
            }

            if (!File.Exists(path))
            {
                SendTo(pf, new TeamMessage { t = "fmiss", f = path });
                return;
            }

            TeamStandIns.RepairIfNeeded(path);
            if (!pf.Agreed.ContainsKey(path) && Phase == TeamSyncPhase.Live)
                MarkAwaiting(pf, path);
            try
            {
                var current = new Outgoing
                {
                    Forced = pf.ForcedSends.Remove(path),
                    Base = pf.BaseOf.ContainsKey(path) ? pf.BaseOf[path] : (pf.Agreed.ContainsKey(path) ? pf.Agreed[path] : null),
                    Path = path,
                    Stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite),
                    Md5 = MD5.Create(),
                    Meta = meta,
                    MetaHash = HashOf(path + ".meta"),
                    Mtime = Math.Max(File.GetLastWriteTimeUtc(path).Ticks, MtimeOf(path + ".meta"))
                };
                pf.Current = current;
                int start;
                if (pf.StartChunk.TryGetValue(path, out start))
                {
                    pf.StartChunk.Remove(path);
                    long skip = (long)start * ChunkSize;
                    if (skip > 0 && skip < current.Stream.Length)
                    {
                        var buffer = new byte[ChunkSize];
                        for (int i = 0; i < start; i++)
                        {
                            int read = current.Stream.Read(buffer, 0, buffer.Length);
                            current.Md5.TransformBlock(buffer, 0, read, null, 0);
                        }
                        current.Index = start;
                    }
                }
                AddRecent((current.Index > 0 ? "Continuing " : "Sending ") + path + (TeamSession.IsHost && peers.Count > 1 ? " to " + pf.Name : string.Empty));
            }
            catch (Exception e)
            {
                AddRecent("Could not read " + path + ": " + e.Message);
                SendTo(pf, new TeamMessage { t = "fmiss", f = path });
            }
        }

        // ---- Receiving --------------------------------------------------------------------------------------------

        private static string IncomingFolder
        {
            get
            {
                string folder = Path.Combine("Library", "WPFMATeam", "in");
                Directory.CreateDirectory(folder);
                return folder;
            }
        }

        private static void ReceiveChunk(PeerFiles pf, TeamMessage message, byte[] blob)
        {
            string path = message.f;
            if (!Shared(path))
            {
                if (message.on)
                    Confirm(pf, new[] { path });
                if (requested.Remove(path))
                    CheckDownloadDone();
                return;
            }

            var incoming = pf.Incoming;
            lastChunkAt = TeamSession.Now;
            Incoming item;

            if (message.n == 0)
            {
                if (incoming.TryGetValue(path, out item))
                {
                    CloseQuietly(item.Stream);
                    DeleteQuietly(item.Temp);
                }

                string temp = Path.Combine(IncomingFolder, Guid.NewGuid().ToString("N") + ".part");
                long mtime;
                long.TryParse(message.mt, NumberStyles.Integer, CultureInfo.InvariantCulture, out mtime);
                item = new Incoming
                {
                    Path = path,
                    Temp = temp,
                    Meta = message.d,
                    Mtime = mtime,
                    Stream = new FileStream(temp, FileMode.Create, FileAccess.Write),
                    Requested = requested.Contains(path),
                    Forced = message.o,
                    Base = message.s
                };
                incoming[path] = item;
            }
            else if (!incoming.TryGetValue(path, out item) || item.Next != message.n)
            {
                return;
            }
            else
            {
                long stamp;
                long.TryParse(message.mt, NumberStyles.Integer, CultureInfo.InvariantCulture, out stamp);
                if (stamp != 0 && item.Mtime != 0 && stamp != item.Mtime)
                {
                    // The file changed on their side since the first part: start it over.
                    CloseQuietly(item.Stream);
                    DeleteQuietly(item.Temp);
                    incoming.Remove(path);
                    SendTo(pf, new TeamMessage { t = "get", a = new[] { path }, b = new[] { "0" } });
                    return;
                }
                if (item.Stream == null)
                    return;
            }

            if (blob != null && blob.Length > 0)
            {
                item.Stream.Write(blob, 0, blob.Length);
                if (item.Requested)
                    DownloadDone += blob.Length;
            }
            item.Next++;

            if (!message.on)
                return;

            CloseQuietly(item.Stream);
            incoming.Remove(path);

            var file = new TeamPendingCode
            {
                Path = path,
                Temp = item.Temp,
                Meta = item.Meta,
                Hash = message.h,
                Mtime = item.Mtime,
                Size = new FileInfo(item.Temp).Length,
                Forced = item.Forced,
                Base = item.Base,
                From = pf.Id
            };

            if (IsCode(path) && !trust)
            {
                Pending.RemoveAll(p => p.Path == path);
                Pending.Add(file);
                Confirm(pf, new[] { path });
                AddRecent("Waiting for trust: " + path);
                if (requested.Remove(path))
                    CheckDownloadDone();
                TeamSession.Raise();
                return;
            }

            ready.RemoveAll(p => p.Path == path);
            ready.Add(file);
        }

        private static void ReceiveFolder(PeerFiles pf, TeamMessage message)
        {
            string path = message.f;
            if (!Shared(path))
                return;
            bool isNew = !Directory.Exists(path);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
                needRefresh = true;
                expectWrite[path] = "dir";
            }
            if (ValidMeta(message.d) && !File.Exists(path + ".meta"))
            {
                File.WriteAllText(path + ".meta", message.d);
                needRefresh = true;
            }
            known[path] = "dir:" + HashOf(path + ".meta");
            pf.Agreed[path] = known[path];
            if (requested.Remove(path))
                CheckDownloadDone();
            // Host: a guest's new folder goes on to the others.
            if (TeamSession.IsHost && isNew)
                EnqueueAll(path, pf);
        }

        private static void ReceiveDelete(PeerFiles pf, string path)
        {
            if (!Shared(path) || TeamScene.IsLive(path))
                return;
            known.Remove(path);
            pf.Agreed.Remove(path);
            if (!File.Exists(path) && !Directory.Exists(path))
                return;

            Backup(path);
            expectDelete.Add(path);
            AssetDatabase.DeleteAsset(path);
            AddRecent(pf.Name + " deleted " + path);
            if (TeamSession.IsHost)
                RelayDelete(pf, path);
        }

        /// <summary>Host: a guest deleted something; the other guests delete it too.</summary>
        private static void RelayDelete(PeerFiles from, string path)
        {
            foreach (var pf in Linked)
            {
                if (pf == from)
                    continue;
                pf.Agreed.Remove(path);
                pf.SendQueue.Remove(path);
                ClearAwaiting(pf, path);
                SendTo(pf, new TeamMessage { t = "fdel", f = path });
            }
        }

        private static void ReceiveMove(PeerFiles pf, string from, string to)
        {
            if (!Shared(from) || !Shared(to))
                return;
            if (!File.Exists(from) && !Directory.Exists(from))
                return;
            if (File.Exists(to) || Directory.Exists(to))
                return;

            string folder = Path.GetDirectoryName(to);
            if (!string.IsNullOrEmpty(folder) && !AssetDatabase.IsValidFolder(folder.Replace('\\', '/')))
            {
                Directory.CreateDirectory(folder);
                AssetDatabase.Refresh();
            }

            expectMove.Add(to);
            string error = AssetDatabase.MoveAsset(from, to);
            if (!string.IsNullOrEmpty(error))
            {
                expectMove.Remove(to);
                AddRecent("Could not move " + from + ": " + error);
                return;
            }

            MoveVersions(from, to);
            AddRecent(pf.Name + " moved " + from + " to " + to);
            if (TeamSession.IsHost)
                foreach (var other in Linked)
                    if (other != pf)
                        SendTo(other, new TeamMessage { t = "fmove", f = from, m = to });
        }

        /// <summary>Writes received files into the project. Scripts wait until nothing else is arriving, so Unity compiles once.</summary>
        private static void ApplyReady()
        {
            if (ready.Count == 0)
                return;
            if (EditorApplication.isPlayingOrWillChangePlaymode || EditorApplication.isCompiling || EditorApplication.isUpdating)
                return;

            bool quiet = PartialCount == 0 && TeamSession.Now - lastChunkAt > 0.75;
            // A material you are editing right now is updated once you pause, so it never reloads mid-edit.
            var batch = ready.Where(r => (!IsCode(r.Path) || quiet) && (Phase != TeamSyncPhase.Live || !EditingNow(r.Path))).ToList();
            if (batch.Count == 0)
                return;

            var toWrite = new List<TeamPendingCode>();
            foreach (var file in batch)
            {
                ready.Remove(file);
                if (reunionPulls.Contains(file.Path) && TeamScene.IsLoaded(file.Path))
                    reopenAfter.Add(file.Path);
                else if (TeamScene.IsLoaded(file.Path))
                {
                    // A scene open here (but not shared) is updated when you close it, not under your feet.
                    if (!TeamScene.IsLive(file.Path))
                    {
                        TeamPendingCode older;
                        if (heldScenes.TryGetValue(file.Path, out older))
                            DeleteQuietly(older.Temp);
                        heldScenes[file.Path] = file;
                        AddRecent(NameOf(file) + " changed " + file.Path + "; it updates when you close it");
                    }
                    else
                        DeleteQuietly(file.Temp);
                    if (requested.Remove(file.Path))
                        CheckDownloadDone();
                    continue;
                }

                // Exactly what is here already (a teammate's save of values that reached us live): nothing to write, so
                // nothing reloads. The others still get it, so everyone knows it is the shared version.
                if (File.Exists(file.Path) && !string.IsNullOrEmpty(file.Hash) && CachedHash(file.Path) == file.Hash)
                {
                    DeleteQuietly(file.Temp);
                    known[file.Path] = file.Hash;
                    var source = For(file.From);
                    if (source != null)
                        source.Agreed[file.Path] = file.Hash;
                    valuesFromTeammate.Remove(file.Path);
                    if (requested.Remove(file.Path))
                        CheckDownloadDone();
                    if (TeamSession.IsHost)
                        EnqueueAll(file.Path, source);
                    ReunionArrived(file.Path, file.From);
                    continue;
                }

                if (Clashes(file))
                {
                    if (TeamSession.IsHost)
                    {
                        // The host's version wins: keep it, send it back, and save the guest's copy.
                        SaveClash(file);
                        Enqueue(For(file.From), file.Path, true);
                        hostKept.Add(NameOf(file) + "\u0001" + file.Path);
                        if (requested.Remove(file.Path))
                            CheckDownloadDone();
                        continue;
                    }
                    guestReplaced.Add(NameOf(file) + "\u0001" + file.Path);
                }
                else if (file.Forced && !TeamSession.IsHost && Phase == TeamSyncPhase.Live && File.Exists(file.Path) && CachedHash(file.Path) != file.Hash)
                {
                    // The host kept its version over our edit and sent it back.
                    guestReplaced.Add(NameOf(file) + "\u0001" + file.Path);
                }

                toWrite.Add(file);
            }
            ReportClashes();

            if (toWrite.Count > 0 && Phase == TeamSyncPhase.Live)
                LogChanges(toWrite.Select(f => f.Path).ToList());

            // A material edited here a moment ago keeps that edit when an older saved copy arrives from the teammate.
            var keepEdits = new Dictionary<string, string>();
            foreach (var file in toWrite)
            {
                if (!file.Path.EndsWith(".mat", StringComparison.OrdinalIgnoreCase) && !file.Path.EndsWith(".asset", StringComparison.OrdinalIgnoreCase))
                    continue;
                var asset = AssetDatabase.LoadMainAssetAtPath(file.Path);
                if (TeamScene.LiveAsset(asset) && TeamScene.RecentlyEdited(asset) && !TeamStandIns.IsStandIn(asset))
                    keepEdits[file.Path] = EditorJsonUtility.ToJson(asset);
            }

            foreach (var file in toWrite)
            {
                try
                {
                    WriteFile(file);
                }
                catch (Exception e)
                {
                    AddRecent("Could not write " + file.Path + ": " + e.Message);
                }

                requested.Remove(file.Path);
                ReunionArrived(file.Path, file.From);
            }
            foreach (var path in reopenAfter)
                ReopenScene(path);
            reopenAfter.Clear();

            // Mark the download finished before Refresh: Refresh may compile scripts and reload Unity right away.
            CheckDownloadDone();
            Save();
            // Confirm before Refresh too: importing scripts can reload Unity before the next line runs.
            foreach (var group in batch.GroupBy(f => f.From ?? string.Empty))
                Confirm(For(group.Key), group.Select(f => f.Path));

            // Host: what a guest sent goes on to the other guests (the host's project is everyone's reference).
            if (TeamSession.IsHost)
                foreach (var file in toWrite)
                    EnqueueAll(file.Path, For(file.From));

            AssetDatabase.Refresh();
            needRefresh = false;

            foreach (var pair in keepEdits)
            {
                var asset = AssetDatabase.LoadMainAssetAtPath(pair.Key);
                if (asset == null)
                    continue;
                EditorJsonUtility.FromJsonOverwrite(pair.Value, asset);
                TeamScene.ResendAsset(asset);
            }

            CheckDownloadDone();
            TeamScene.FilesArrived();
            foreach (var file in toWrite)
                TeamScene.ChangedByTeammate(AssetDatabase.LoadMainAssetAtPath(file.Path));

            ReloadPrefabStage(toWrite);
        }

        // "name\u0001path" so each note names who it was with.
        private static readonly List<string> hostKept = new List<string>();
        private static readonly List<string> guestReplaced = new List<string>();

        private static string NameOf(TeamPendingCode file)
        {
            PeerFiles pf;
            if (file != null && !string.IsNullOrEmpty(file.From) && peers.TryGetValue(file.From, out pf))
                return pf.Name;
            return TeamSession.RemoteName ?? "Your teammate";
        }

        /// <summary>
        /// Every change says which version it was made on top of. If ours is neither that version nor theirs, we
        /// both changed the same starting version at the same time.
        /// </summary>
        private static bool Clashes(TeamPendingCode file)
        {
            if (reunionAccept.Remove(file.Path))
                return false;
            if (file.Forced || Phase != TeamSyncPhase.Live || !File.Exists(file.Path))
                return false;
            string mine = CachedHash(file.Path);
            if (mine == file.Hash)
                return false;
            // We only saved their own live edits here (a material they are tweaking): their file is simply newer.
            if (OnlyTheirLiveEdits(file))
                return false;
            // Both made a new file at the same path: the host's stays.
            if (string.IsNullOrEmpty(file.Base))
                return TeamSession.IsHost;
            return mine != file.Base;
        }

        /// <summary>Unity ignores (and then treats as deleted) an asset whose .meta has no GUID, so never write one.</summary>
        private static bool ValidMeta(string meta)
        {
            return !string.IsNullOrEmpty(meta) && meta.Contains("guid:");
        }

        private static string ClashFolder
        {
            get { return Path.Combine(Path.GetDirectoryName(Application.dataPath), "WPFMA-Snapshots", "Team", "conflicts", DateTime.Now.ToString("yyyyMMdd-HHmmss")); }
        }

        private static void SaveClash(TeamPendingCode file)
        {
            try
            {
                string target = Path.Combine(ClashFolder, file.Path);
                Directory.CreateDirectory(Path.GetDirectoryName(target));
                File.Copy(file.Temp, target, true);
            }
            catch (Exception)
            {
            }
            DeleteQuietly(file.Temp);
        }

        private static string Names(List<string> paths)
        {
            var names = paths.Take(3).Select(Path.GetFileName).ToList();
            return string.Join(", ", names.ToArray()) + (paths.Count > 3 ? " and " + (paths.Count - 3) + " more" : string.Empty);
        }

        private static void ReportClashes()
        {
            foreach (var group in hostKept.Select(k => k.Split('\u0001')).GroupBy(k => k[0]).ToList())
            {
                string name = group.Key;
                var paths = group.Select(k => k[1]).ToList();
                foreach (var path in paths)
                    AddRecent("Kept your " + path + " (" + name + " changed it at the same time)");
                TeamSession.AddSystem(name + " changed " + Names(paths) + " at the same time as you. As host, your version is kept and sent to them; " +
                                      "theirs is saved in WPFMA-Snapshots/Team/conflicts.");
            }
            hostKept.Clear();
            if (guestReplaced.Count > 0)
            {
                string name = guestReplaced[0].Split('\u0001')[0];
                var paths = guestReplaced.Select(k => k.Split('\u0001')[1]).ToList();
                foreach (var path in paths)
                    AddRecent(name + "'s version replaced your edit of " + path);
                TeamSession.AddSystem(name + " (host) changed " + Names(paths) + " while you were editing. You now have the host's version; " +
                                      "yours is saved in WPFMA-Snapshots/Team.");
                TeamToasts.Show("Host's version of " + Names(paths));
                guestReplaced.Clear();
            }
        }

        private static readonly Dictionary<string, TeamPendingCode> heldScenes = new Dictionary<string, TeamPendingCode>();

        private static void ApplyHeldScene(string path)
        {
            TeamPendingCode file;
            if (!heldScenes.TryGetValue(path, out file))
                return;
            // Opened again, or opened together (which brings a newer copy): the held one is out of date.
            if (TeamScene.IsLoaded(path) || TeamScene.IsLive(path))
            {
                if (TeamScene.IsLive(path))
                {
                    heldScenes.Remove(path);
                    DeleteQuietly(file.Temp);
                }
                return;
            }
            heldScenes.Remove(path);
            try
            {
                WriteFile(file);
                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                AddRecent("Could not update " + path + ": " + e.Message);
            }
        }

        /// <summary>Teammate changes go into the Change log, grouped into one entry per couple of minutes.</summary>
        private static void LogChanges(List<string> paths)
        {
            var existing = paths.Where(File.Exists).ToList();
            var created = paths.Where(p => !File.Exists(p)).ToList();
            string who = TeamSession.RemoteName ?? "Your teammate";
            string result = who + " changed files";
            if (logEntry == null || logEntry.reverted || TeamSession.Now - logEntryAt > 120)
            {
                logEntry = WPFMAChangeLog.Begin("Team", "Files from " + who + " (" + DateTime.Now.ToString("HH:mm") + ")", existing, false, result);
                if (logEntry != null)
                    WPFMAChangeLog.AddAssets(logEntry, null, created, null);
            }
            else
            {
                WPFMAChangeLog.AddAssets(logEntry, existing, created, null);
            }
            logEntryAt = TeamSession.Now;
        }

        /// <summary>When a prefab you have open in Prefab Mode changes on their side, reopen it to show their version.</summary>
        private static void ReloadPrefabStage(List<TeamPendingCode> written)
        {
            var stage = UnityEditor.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
            if (stage == null || !written.Any(f => f.Path == stage.assetPath))
                return;
            if (stage.scene.isDirty)
            {
                TeamSession.AddSystem(TeamSession.RemoteName + " changed " + Path.GetFileName(stage.assetPath) +
                                      ", which you have open with unsaved changes. Save or discard yours to see theirs.");
                return;
            }
            string path = stage.assetPath;
            EditorApplication.delayCall += () => UnityEditor.SceneManagement.PrefabStageUtility.OpenPrefab(path);
        }

        private static void PeriodicWork()
        {
            if (TeamSession.Now - lastPeriodicSave < 5.0)
                return;
            lastPeriodicSave = TeamSession.Now;

            foreach (var pf in peers.Values)
            {
                foreach (var pair in pf.AwaitingSince.ToList())
                {
                    if (TeamSession.Now - pair.Value > 600)
                    {
                        pf.Awaiting.Remove(pair.Key);
                        pf.AwaitingSince.Remove(pair.Key);
                    }
                }
            }

            // Tools and scripts often change assets without Undo, which sends no change event. Saving dirty assets
            // every few seconds (while nobody is mid-edit) makes those reach the teammate too.
            // (Not while something you have open in the Inspector has unsaved edits: it would save that too.)
            if (Active && AutoSave && TeamScene.SecondsSinceLocalEdit > 2.0 && !EditorApplication.isPlayingOrWillChangePlaymode &&
                !EditorApplication.isCompiling && !EditorApplication.isUpdating && !InspectedNow().Any(EditorUtility.IsDirty))
                AssetDatabase.SaveAssets();
        }

        /// <summary>Called for every asset edit; the asset is saved once it has been left alone for a moment.</summary>
        /// <summary>
        /// Assets whose values a teammate just changed live (materials, menus...). When Unity saves them here, that
        /// save is not sent back: the teammate sends their own copy. Sending it back made the asset reload under the
        /// person editing it, which disconnected their Inspector and color picker after every change.
        /// </summary>
        private static readonly Dictionary<string, double> valuesFromTeammate = new Dictionary<string, double>();

        // Who last changed an asset's values live here (path -> teammate id, time), until someone here edits it.
        private static readonly Dictionary<string, KeyValuePair<string, double>> liveSource = new Dictionary<string, KeyValuePair<string, double>>();

        internal static void ValuesFromTeammate(string path, TeamPeer from)
        {
            if (string.IsNullOrEmpty(path))
                return;
            valuesFromTeammate[path] = TeamSession.Now;
            liveSource[path] = new KeyValuePair<string, double>(from != null ? from.Id : string.Empty, TeamSession.Now);
        }

        /// <summary>
        /// Our copy of this file only differs from what it was because of live edits that came from a teammate (and
        /// that this file carries), not because someone here edited it.
        /// </summary>
        private static bool OnlyTheirLiveEdits(TeamPendingCode file)
        {
            KeyValuePair<string, double> source;
            if (!liveSource.TryGetValue(file.Path, out source) || TeamSession.Now - source.Value > 300)
                return false;
            // A guest takes the host's file anyway; the host checks it's the same teammate whose edits these were.
            return !TeamSession.IsHost || source.Key == file.From;
        }

        /// <summary>True while someone here is in the middle of editing this live asset (keep it from reloading under them).</summary>
        private static bool EditingNow(string path)
        {
            if (!path.EndsWith(".mat", StringComparison.OrdinalIgnoreCase) && !path.EndsWith(".asset", StringComparison.OrdinalIgnoreCase))
                return false;
            var asset = AssetDatabase.LoadMainAssetAtPath(path);
            if (asset == null || !TeamScene.LiveAsset(asset))
                return false;
            // Open in your Inspector, or edited a moment ago: it updates once you click off.
            return InspectedNow().Contains(asset.GetInstanceID()) || TeamScene.RecentlyEdited(asset, 3.0);
        }

        internal static void AssetTouched(int instanceId)
        {
            // A real edit: from now on its saves are yours, not Unity re-saving what just arrived.
            var touched = EditorUtility.InstanceIDToObject(instanceId);
            if (touched != null && (justWrote.Count > 0 || valuesFromTeammate.Count > 0 || liveSource.Count > 0))
            {
                string touchedPath = AssetDatabase.GetAssetPath(touched);
                justWrote.Remove(touchedPath);
                valuesFromTeammate.Remove(touchedPath);
                liveSource.Remove(touchedPath);
            }
            if (Active && AutoSave)
                touchedAssets[instanceId] = TeamSession.Now;
        }

        /// <summary>
        /// Assets open in an Inspector right now (selected, or a material shown under a selected object). While you
        /// have one open it isn't saved or replaced: saving it under an open Inspector stopped the next edit from
        /// taking until you clicked off and back on. Teammates still see your changes live meanwhile; the file
        /// follows as soon as you click off.
        /// </summary>
        private static HashSet<int> InspectedNow()
        {
            if (inspectedFrame == Time.frameCount && inspectedAt == TeamSession.Now)
                return inspected;
            inspectedFrame = Time.frameCount;
            inspectedAt = TeamSession.Now;
            inspected.Clear();
            try
            {
                foreach (var editor in ActiveEditorTracker.sharedTracker.activeEditors)
                    if (editor != null)
                        foreach (var target in editor.targets)
                            if (target != null && EditorUtility.IsPersistent(target))
                                inspected.Add(target.GetInstanceID());
            }
            catch (Exception)
            {
            }
            foreach (var selected in Selection.objects)
                if (selected != null && EditorUtility.IsPersistent(selected))
                    inspected.Add(selected.GetInstanceID());
            return inspected;
        }

        private static readonly HashSet<int> inspected = new HashSet<int>();
        private static int inspectedFrame = -1;
        private static double inspectedAt = -1;

        private static void SaveTouchedAssets()
        {
            if (touchedAssets.Count == 0 || TeamSession.Now - lastAutoSave < 0.25 || EditorApplication.isPlayingOrWillChangePlaymode)
                return;
            lastAutoSave = TeamSession.Now;

            var open = InspectedNow();
            foreach (var pair in touchedAssets.ToList())
            {
                if (TeamSession.Now - pair.Value < 0.75)
                    continue;
                // Still open in the Inspector: wait until you click off it.
                if (open.Contains(pair.Key))
                    continue;
                touchedAssets.Remove(pair.Key);

                var asset = EditorUtility.InstanceIDToObject(pair.Key);
                if (asset == null || TeamStandIns.IsStandIn(asset))
                    continue;
                string path = AssetDatabase.GetAssetPath(asset);
                if (string.IsNullOrEmpty(path) || !Shared(path) || path.EndsWith(".unity", StringComparison.OrdinalIgnoreCase))
                    continue;
                string guid = AssetDatabase.AssetPathToGUID(path);
                if (!string.IsNullOrEmpty(guid))
                    AssetDatabase.SaveAssetIfDirty(new GUID(guid));
            }
        }

        private static void WriteFile(TeamPendingCode file)
        {
            string folder = Path.GetDirectoryName(file.Path);
            if (!string.IsNullOrEmpty(folder))
                Directory.CreateDirectory(folder);

            if (File.Exists(file.Path))
                Backup(file.Path);
            // Anything of ours still going out for this file is out of date now.
            foreach (var pf in peers.Values)
            {
                pf.SendQueue.Remove(file.Path);
                pf.BaseOf.Remove(file.Path);
                if (pf.Current != null && pf.Current.Path == file.Path)
                {
                    CloseQuietly(pf.Current.Stream);
                    pf.Current = null;
                }
            }
            TeamStandIns.Forget(file.Path);

            bool hasMeta = ValidMeta(file.Meta);
            if (hasMeta)
                File.WriteAllText(file.Path + ".meta", file.Meta, new UTF8Encoding(false));
            File.Copy(file.Temp, file.Path, true);
            DeleteQuietly(file.Temp);

            if (file.Mtime > 0)
            {
                try
                {
                    var stamp = new DateTime(file.Mtime, DateTimeKind.Utc);
                    File.SetLastWriteTimeUtc(file.Path, stamp);
                    if (hasMeta)
                        File.SetLastWriteTimeUtc(file.Path + ".meta", stamp);
                }
                catch (Exception)
                {
                }
            }

            justWrote[file.Path] = TeamSession.Now;
            if (!string.IsNullOrEmpty(file.Hash))
            {
                expectWrite[file.Path] = file.Hash;
                known[file.Path] = file.Hash;
                var source = For(file.From);
                if (source != null)
                    source.Agreed[file.Path] = file.Hash;
            }
            AddRecent("Received " + file.Path + (TeamSession.IsHost && peers.Count > 1 ? " from " + NameOf(file) : string.Empty));
        }

        internal static void Accept(TeamPendingCode file)
        {
            if (Pending.Remove(file))
                ready.Add(file);
            TeamSession.Raise();
        }

        internal static void AcceptAll()
        {
            ready.AddRange(Pending);
            Pending.Clear();
            TeamSession.Raise();
        }

        internal static void Reject(TeamPendingCode file)
        {
            if (Pending.Remove(file))
                DeleteQuietly(file.Temp);
            AddRecent("Did not apply " + file.Path);
            TeamSession.Raise();
        }

        // ---- Local changes ----------------------------------------------------------------------------------------

        internal static void OnAssets(string[] imported, string[] deleted, string[] moved, string[] movedFrom)
        {
            if (!Active)
            {
                foreach (var path in imported)
                    expectWrite.Remove(path);
                return;
            }

            foreach (var path in deleted)
            {
                if (expectDelete.Remove(path) || !Shared(path))
                    continue;
                known.Remove(path);
                foreach (var pf in peers.Values)
                {
                    pf.Agreed.Remove(path);
                    pf.SendQueue.Remove(path);
                }
                ClearAwaitingEverywhere(path);
                if (!TeamScene.IsLive(path))
                    TeamSession.Send(new TeamMessage { t = "fdel", f = path });
            }

            for (int i = 0; i < moved.Length; i++)
            {
                string to = moved[i], from = movedFrom[i];
                if (expectMove.Remove(to))
                    continue;
                bool sharedFrom = Shared(from), sharedTo = Shared(to);
                if (sharedFrom && sharedTo)
                {
                    TeamSession.Send(new TeamMessage { t = "fmove", f = from, m = to });
                    MoveVersions(from, to);
                }
                else if (sharedTo)
                    toCheck.Add(to);
                else if (sharedFrom)
                    TeamSession.Send(new TeamMessage { t = "fdel", f = from });
            }

            foreach (var path in imported)
            {
                if (!Shared(path))
                    continue;
                toCheck.Add(path);
                // Brand new here (not something we just received): nobody else has it until it arrives.
                if (!known.ContainsKey(path) && !expectWrite.ContainsKey(path) && !TeamScene.IsLive(path))
                    foreach (var pf in Linked)
                        if (!pf.Agreed.ContainsKey(path))
                            MarkAwaiting(pf, path);
            }
        }

        private static void MoveVersions(string from, string to)
        {
            string hash;
            if (known.TryGetValue(from, out hash))
            {
                known.Remove(from);
                known[to] = hash;
            }
            foreach (var pf in peers.Values)
            {
                if (pf.Agreed.TryGetValue(from, out hash))
                {
                    pf.Agreed.Remove(from);
                    pf.Agreed[to] = hash;
                }
            }
        }

        /// <summary>
        /// After a scan: the first one sets the baseline. Later ones (after a reload or restart, when the import
        /// events of the gap were lost) find anything that changed or vanished since, and share it.
        /// </summary>
        private static void Reconcile(List<Entry> list)
        {
            if (!knownReady)
            {
                foreach (var e in list)
                {
                    known[e.Path] = e.Hash;
                    if (TeamSession.IsHost)
                        foreach (var pf in peers.Values)
                            if (!pf.Reuniting && !pf.Agreed.ContainsKey(e.Path))
                                pf.Agreed[e.Path] = e.Hash;
                }
                knownReady = true;
                return;
            }

            if (Phase != TeamSyncPhase.Live)
                return;

            var present = new HashSet<string>();
            foreach (var e in list)
            {
                present.Add(e.Path);
                string was;
                if (!known.TryGetValue(e.Path, out was) || was != e.Hash)
                    toCheck.Add(e.Path);
            }

            foreach (var path in known.Keys.ToList())
            {
                if (present.Contains(path) || !Shared(path) || File.Exists(path) || Directory.Exists(path) || TeamScene.IsLive(path))
                    continue;
                known.Remove(path);
                foreach (var pf in peers.Values)
                {
                    if (pf.Reuniting)
                        continue;
                    pf.Agreed.Remove(path);
                    SendTo(pf, new TeamMessage { t = "fdel", f = path });
                }
                AddRecent("Deleted while apart: " + path);
            }
        }

        private static void ProcessChecks()
        {
            if (toCheck.Count == 0 || !knownReady)
                return;

            double started = TeamSession.Now;
            foreach (var path in toCheck.ToList())
            {
                if (TeamSession.Now - started > 0.03)
                    break;
                toCheck.Remove(path);

                string hash;
                TeamStandIns.RepairIfNeeded(path);
                if (Directory.Exists(path))
                    hash = "dir:" + HashOf(path + ".meta");
                else if (File.Exists(path))
                    hash = CachedHash(path);
                else
                    continue;

                string expect;
                if (expectWrite.TryGetValue(path, out expect))
                {
                    expectWrite.Remove(path);
                    if (expect == hash || expect == "dir")
                    {
                        known[path] = hash;
                        continue;
                    }
                }

                // Unity (or a package's importer) re-saved a file we just received: keep the host's as the
                // reference and don't send the re-saved copy back.
                double wrote;
                if (justWrote.TryGetValue(path, out wrote) && TeamSession.Now - wrote < 3.0)
                {
                    known[path] = hash;
                    continue;
                }

                // Unity saved values a teammate changed live: they send their own copy, so don't send ours back.
                double fromTeammate;
                if (valuesFromTeammate.TryGetValue(path, out fromTeammate))
                {
                    valuesFromTeammate.Remove(path);
                    if (TeamSession.Now - fromTeammate < 60.0)
                    {
                        known[path] = hash;
                        continue;
                    }
                }

                string was;
                if (known.TryGetValue(path, out was) && was == hash)
                    continue;
                known[path] = hash;

                // A shared scene reaches the teammates editing it live; the others (in other scenes) get the saved file.
                bool liveHere = TeamScene.IsLive(path);
                foreach (var pf in Linked)
                {
                    if (pf.Reuniting || (liveHere && TeamScene.SharedWith(pf.Id, path)))
                        continue;
                    if (!pf.BaseOf.ContainsKey(path))
                        pf.BaseOf[path] = pf.Agreed.ContainsKey(path) ? pf.Agreed[path] : string.Empty;
                    Enqueue(pf, path);
                }
            }
        }

        // ---- Update -----------------------------------------------------------------------------------------------

        private static void Update()
        {
            if (scan != null && scan.IsCompleted)
            {
                var finished = scan;
                scan = null;
                lastScan = finished.Status == TaskStatus.RanToCompletion ? finished.Result : new List<Entry>();
                Reconcile(lastScan);
                SaveCache();

                var waiting = afterScan.ToList();
                afterScan.Clear();
                bool diffed = false;
                foreach (var then in waiting)
                {
                    if (then != null)
                    {
                        try
                        {
                            then(lastScan);
                        }
                        catch (Exception e)
                        {
                            Debug.LogException(e);
                        }
                    }
                    else if (!diffed)
                    {
                        diffed = true;
                        TryDiff();
                    }
                }
            }

            if (!TeamSession.IsLinked)
                return;

            ProcessChecks();
            SaveTouchedAssets();
            PeriodicWork();
            PumpCheck();
            PumpSend();
            ApplyReady();
            if (needRefresh && !EditorApplication.isPlayingOrWillChangePlaymode)
            {
                needRefresh = false;
                AssetDatabase.Refresh();
            }
        }

        // ---- Helpers ----------------------------------------------------------------------------------------------

        private static void Backup(string path)
        {
            try
            {
                if (backupFolder == null)
                    backupFolder = Path.Combine(Path.GetDirectoryName(Application.dataPath), "WPFMA-Snapshots", "Team", DateTime.Now.ToString("yyyyMMdd-HHmmss"));

                string target = Path.Combine(backupFolder, path);
                Directory.CreateDirectory(Path.GetDirectoryName(target));
                if (File.Exists(path))
                {
                    File.Copy(path, target, true);
                    if (File.Exists(path + ".meta"))
                        File.Copy(path + ".meta", target + ".meta", true);
                }
            }
            catch (Exception)
            {
            }
        }

        internal static string BackupFolder
        {
            get { return backupFolder; }
        }

        private static string CachedHash(string path)
        {
            try
            {
                var info = new FileInfo(path);
                long mtime = Math.Max(info.LastWriteTimeUtc.Ticks, MtimeOf(path + ".meta"));
                lock (cache)
                {
                    CacheEntry cached;
                    if (cache.TryGetValue(path, out cached) && cached.Size == info.Length && cached.Mtime == mtime)
                        return cached.Hash;
                }

                string hash = HashOf(path) + ":" + HashOf(path + ".meta");
                lock (cache)
                    cache[path] = new CacheEntry { Size = info.Length, Mtime = mtime, Hash = hash };
                return hash;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        private static string HashOf(string path)
        {
            try
            {
                if (!File.Exists(path))
                    return string.Empty;
                using (var md5 = MD5.Create())
                using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    return Hex(md5.ComputeHash(stream));
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        private static long MtimeOf(string path)
        {
            try
            {
                return File.Exists(path) ? File.GetLastWriteTimeUtc(path).Ticks : 0;
            }
            catch (Exception)
            {
                return 0;
            }
        }

        private static string Hex(byte[] bytes)
        {
            return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLowerInvariant();
        }

        private static string CachePath
        {
            get { return Path.Combine("Library", "WPFMATeamHashes.txt"); }
        }

        private static void LoadCache()
        {
            if (cacheLoaded)
                return;
            cacheLoaded = true;
            try
            {
                if (!File.Exists(CachePath))
                    return;
                lock (cache)
                {
                    foreach (var line in File.ReadAllLines(CachePath))
                    {
                        var parts = line.Split('\t');
                        long size, mtime;
                        if (parts.Length == 4 && long.TryParse(parts[1], out size) && long.TryParse(parts[2], out mtime))
                            cache[parts[0]] = new CacheEntry { Size = size, Mtime = mtime, Hash = parts[3] };
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private static void SaveCache()
        {
            try
            {
                var lines = new List<string>();
                lock (cache)
                    foreach (var pair in cache)
                        lines.Add(pair.Key + "\t" + pair.Value.Size + "\t" + pair.Value.Mtime + "\t" + pair.Value.Hash);
                File.WriteAllLines(CachePath, lines.ToArray());
            }
            catch (Exception)
            {
            }
        }

        private static void AddRecent(string text)
        {
            Recent.Add(DateTime.Now.ToString("HH:mm:ss") + "  " + text);
            while (Recent.Count > 40)
                Recent.RemoveAt(0);
        }

        private static FileStream OpenAppend(string path)
        {
            try
            {
                return new FileStream(path, FileMode.Append, FileAccess.Write);
            }
            catch (Exception)
            {
                return null;
            }
        }

        private static void CloseQuietly(Stream stream)
        {
            try
            {
                if (stream != null)
                    stream.Dispose();
            }
            catch (Exception)
            {
            }
        }

        private static void DeleteQuietly(string path)
        {
            try
            {
                if (!string.IsNullOrEmpty(path) && File.Exists(path))
                    File.Delete(path);
            }
            catch (Exception)
            {
            }
        }
    }

    internal sealed class TeamFilesWatcher : AssetPostprocessor
    {
        private static void OnPostprocessAllAssets(string[] imported, string[] deleted, string[] moved, string[] movedFrom)
        {
            TeamFiles.OnAssets(imported, deleted, moved, movedFrom);
        }
    }

    /// <summary>Read-only view of a script the teammate sent, so it can be checked before trusting it.</summary>
    internal sealed class TeamCodeView : EditorWindow
    {
        private TeamPendingCode file;
        private string text;
        private Vector2 scroll;

        internal static void Show(TeamPendingCode file)
        {
            var window = CreateInstance<TeamCodeView>();
            window.file = file;
            window.titleContent = new GUIContent(Path.GetFileName(file.Path));
            try
            {
                window.text = file.Size > 2 * 1024 * 1024 || !File.Exists(file.Temp)
                    ? "(This file is too large or binary to show here.)"
                    : File.ReadAllText(file.Temp);
            }
            catch (Exception e)
            {
                window.text = "(Could not read the file: " + e.Message + ")";
            }
            window.minSize = new Vector2(520, 360);
            window.ShowUtility();
        }

        private void OnGUI()
        {
            if (file == null)
            {
                Close();
                return;
            }

            EditorGUILayout.LabelField(file.Path, EditorStyles.boldLabel);
            EditorGUILayout.LabelField("Sent by " + (TeamSession.RemoteName ?? "your teammate") + ". It is not in your project until you accept it.", EditorStyles.miniLabel);

            scroll = EditorGUILayout.BeginScrollView(scroll);
            var style = new GUIStyle(EditorStyles.textArea) { wordWrap = false, font = EditorStyles.standardFont, richText = false };
            EditorGUILayout.SelectableLabel(text, style, GUILayout.ExpandHeight(true), GUILayout.MinHeight(Mathf.Max(200, style.CalcSize(new GUIContent(text)).y)));
            EditorGUILayout.EndScrollView();

            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Don't apply", GUILayout.Width(110)))
                {
                    TeamFiles.Reject(file);
                    Close();
                }
                if (GUILayout.Button("Accept", GUILayout.Width(110)))
                {
                    TeamFiles.Accept(file);
                    Close();
                }
            }
        }
    }
}
#endif
