// 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.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace WPFMA.Team
{
    /// <summary>
    /// The Team tab. Everything is chosen in the setup window before connecting, so this only shows who you're with,
    /// what's happening, chat, and a line when something needs you.
    /// </summary>
    [InitializeOnLoad]
    internal static class TeamPanel
    {
        private static string chatInput = string.Empty;
        private static string joinCode = string.Empty;
        private static Vector2 chatScroll;
        private static int lastChatCount;

        static TeamPanel()
        {
            TeamSession.Changed += () =>
            {
                foreach (var window in Resources.FindObjectsOfTypeAll<WPFMAWindow>())
                    window.Repaint();
            };
        }

        internal static void Draw(GUIStyle sectionStyle, GUIStyle hintStyle)
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(8f);
            EditorGUILayout.BeginVertical(sectionStyle);

            try
            {
                EditorGUILayout.LabelField("Team", new GUIStyle(EditorStyles.boldLabel) { fontSize = 14 });
                switch (TeamSession.State)
                {
                    case TeamState.Idle:
                        DrawIdle();
                        break;
                    case TeamState.Connected:
                        DrawConnected();
                        break;
                    default:
                        DrawConnecting();
                        break;
                }
                DrawChat();
            }
            finally
            {
                EditorGUILayout.EndVertical();
                GUILayout.Space(8f);
                EditorGUILayout.EndHorizontal();
            }
        }

        private static GUIStyle Hint(Color color)
        {
            return WPFMAToolSection.Hint(color);
        }

        // ---- Not connected ------------------------------------------------------------------------------------------

        private static void DrawIdle()
        {
            EditorGUILayout.LabelField("Work in the same project with up to " + TeamSession.MaxGuests + " friends: files, scenes and edits stay in sync as you all work.",
                Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(6f);

            if (!string.IsNullOrEmpty(TeamSession.RejoinNote))
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.LabelField(TeamSession.RejoinNote, new GUIStyle(EditorStyles.boldLabel) { normal = { textColor = WPFMAToolSection.AccentBlue } });
                    if (GUILayout.Button("Cancel", GUILayout.Width(70f)))
                        TeamSession.CancelRejoin();
                }
                EditorGUILayout.Space(4f);
                return;
            }

            if (!string.IsNullOrEmpty(TeamSession.Error))
            {
                EditorGUILayout.HelpBox(TeamSession.Error, MessageType.Warning);
                if (GUILayout.Button("Find out why (Team doctor)", EditorStyles.miniButton, GUILayout.Width(170f)))
                    TeamDoctor.Open();
                EditorGUILayout.Space(4f);
            }

            if (GUILayout.Button("Host a session", GUILayout.Height(32f)))
                TeamSetupWindow.Open(TeamSetupWindow.Mode.Host);

            EditorGUILayout.Space(4f);
            using (new EditorGUILayout.HorizontalScope())
            {
                joinCode = EditorGUILayout.TextField(joinCode, GUILayout.Height(32f)).ToUpperInvariant();
                if (string.IsNullOrEmpty(joinCode))
                    GUI.Label(GUILayoutUtility.GetLastRect(), "  Session code", Hint(WPFMAToolSection.FaintText));
                if (GUILayout.Button("Join", GUILayout.Width(110f), GUILayout.Height(32f)))
                    TeamSetupWindow.Open(TeamSetupWindow.Mode.Join, joinCode);
            }

            EditorGUILayout.Space(6f);
            EditorGUILayout.LabelField("Connections go straight between your PCs, so only team up with people you trust (or both use Tailscale).",
                Hint(WPFMAToolSection.FaintText));
            if (GUILayout.Button("Team doctor: check my connection", EditorStyles.miniButton, GUILayout.Width(210f)))
                TeamDoctor.Open();
        }

        // ---- Connecting ---------------------------------------------------------------------------------------------

        private static void DrawConnecting()
        {
            if (TeamSession.IsHost && !string.IsNullOrEmpty(TeamSession.Code) && TeamSession.State != TeamState.Reconnecting)
            {
                EditorGUILayout.LabelField("Send this code to your friends (up to " + TeamSession.MaxGuests + ")", Hint(WPFMAToolSection.FaintText));
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.SelectableLabel(TeamSession.Code,
                        new GUIStyle(EditorStyles.boldLabel) { fontSize = 26, normal = { textColor = TeamSession.LocalColor } }, GUILayout.Height(36f));
                    if (GUILayout.Button("Copy", GUILayout.Width(60f), GUILayout.Height(28f)))
                        EditorGUIUtility.systemCopyBuffer = TeamSession.Code;
                }
            }

            if (!string.IsNullOrEmpty(TeamSession.Status))
                EditorGUILayout.LabelField(TeamSession.Status, new GUIStyle(EditorStyles.boldLabel) { normal = { textColor = WPFMAToolSection.AccentBlue }, wordWrap = true });
            if (TeamSession.Steps.Count > 0 && TeamSession.State != TeamState.Reconnecting)
                EditorGUILayout.LabelField(TeamSession.Steps.Last(), Hint(WPFMAToolSection.FaintText));

            EditorGUILayout.Space(4f);
            if (GUILayout.Button(TeamSession.State == TeamState.Reconnecting ? "Stop and leave" : "Cancel", GUILayout.Width(120f)))
            {
                TeamSession.CancelRejoin();
                EditorApplication.delayCall += () => TeamSession.Leave(TeamSession.State == TeamState.Reconnecting ? "they left" : "cancelled");
            }
        }

        // ---- Connected ----------------------------------------------------------------------------------------------

        private static void DrawConnected()
        {
            TeamSession.Unread = 0;
            string name = TeamSession.RemoteName ?? "Your friend";

            // Everyone else here: host first, then guests, each in their own color.
            foreach (var peer in TeamSession.Peers.OrderBy(p => p.IsHost ? 0 : 1).ToList())
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.LabelField("●  " + peer.Name + (peer.IsHost ? "  (host)" : string.Empty) + (peer.Link != null && !peer.Up ? "  (reconnecting)" : string.Empty),
                        new GUIStyle(EditorStyles.boldLabel) { normal = { textColor = peer.Color } });
                    GUILayout.FlexibleSpace();
                    EditorGUILayout.LabelField(peer.PingMs >= 0 ? peer.PingMs + " ms" : string.Empty, Hint(WPFMAToolSection.FaintText), GUILayout.Width(55f));
                    if (GUILayout.Button(new GUIContent("Jump", "Show what they have selected, or where they are looking"), EditorStyles.miniButtonLeft, GUILayout.Width(48f)))
                        TeamView.JumpToTeammate(peer);
                    bool following = TeamSession.Following && TeamView.FollowTarget == peer;
                    if (GUILayout.Button(new GUIContent(following ? "Unfollow" : "Follow", "Move your view with their camera"), EditorStyles.miniButtonRight, GUILayout.Width(62f)))
                    {
                        TeamSession.FollowId = peer.Id;
                        TeamSession.Following = !following;
                    }
                    if (TeamSession.IsHost && peer.Link != null)
                    {
                        using (new EditorGUI.DisabledScope(!TeamSession.CanHandOff || !peer.Up))
                        {
                            var tip = TeamSession.CanHandOff
                                ? "Pass the session to " + peer.Name + ". Everyone reconnects to them; you stay in as a guest."
                                : "Only sessions started with Host a session (not without the website) can be handed over.";
                            if (GUILayout.Button(new GUIContent("Make host", tip), EditorStyles.miniButton, GUILayout.Width(74f)) &&
                                EditorUtility.DisplayDialog("Make " + peer.Name + " the host?",
                                    "Everyone reconnects to " + peer.Name + " within about " + (6 + 5 * TeamSession.GuestCount) + " seconds, using the same code. " +
                                    "You stay in the session as a guest.\n\n" + peer.Name + "'s project becomes the one everyone matches, so make sure " +
                                    "the Team tab says Ready to upload first.", "Make host", "Cancel"))
                            {
                                var target = peer;
                                EditorApplication.delayCall += () => TeamSession.HandOff(target);
                            }
                        }
                    }
                }
                EditorGUILayout.LabelField(Activity(peer), Hint(WPFMAToolSection.MetaText));
            }

            // The host can bring in more people while there is room.
            if (TeamSession.IsHost && TeamSession.HasRoom && !string.IsNullOrEmpty(TeamSession.Code))
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    int room = TeamSession.MaxGuests - TeamSession.Peers.Count(p => p.Link != null);
                    EditorGUILayout.LabelField("Invite " + (room == 1 ? "one more" : room + " more") + " with code", Hint(WPFMAToolSection.FaintText), GUILayout.Width(150f));
                    EditorGUILayout.SelectableLabel(TeamSession.Code, new GUIStyle(EditorStyles.boldLabel) { normal = { textColor = TeamSession.LocalColor } }, GUILayout.Height(18f));
                    if (GUILayout.Button("Copy", EditorStyles.miniButton, GUILayout.Width(50f)))
                        EditorGUIUtility.systemCopyBuffer = TeamSession.Code;
                }
            }
            EditorGUILayout.Space(4f);

            EditorGUILayout.LabelField(SyncLine(), Hint(SyncColor()));
            if (TeamFiles.Phase == TeamSyncPhase.Downloading)
            {
                float progress = TeamFiles.DownloadTotal > 0 ? Mathf.Clamp01((float)TeamFiles.DownloadDone / TeamFiles.DownloadTotal) : 0f;
                var bar = GUILayoutUtility.GetRect(18f, 16f, GUILayout.ExpandWidth(true));
                EditorGUI.ProgressBar(bar, progress, Size(TeamFiles.DownloadDone) + " of " + Size(TeamFiles.DownloadTotal) + Speed());
            }
            else
            {
                rate = 0;
                sampleAt = -1;
            }

            DrawSceneCheck();
            DrawReady();
            DrawNeedsYou(name);

            EditorGUILayout.Space(6f);
            using (new EditorGUILayout.HorizontalScope())
            {
                if (GUILayout.Button("Settings", GUILayout.Width(90f)))
                    TeamSetupWindow.Open(TeamSetupWindow.Mode.Settings);
                if (GUILayout.Button("Team doctor", GUILayout.Width(100f)))
                    TeamDoctor.Open();
                GUILayout.FlexibleSpace();
                if (GUILayout.Button(TeamSession.IsHost ? "End session" : "Leave", GUILayout.Width(110f)))
                    EditorApplication.delayCall += () => TeamSession.Leave(TeamSession.IsHost ? "the host ended the session" : "they left");
            }
        }

        private static string Ago(double at)
        {
            double seconds = TeamSession.Now - at;
            return seconds < 60 ? (int)seconds + "s ago" : (int)(seconds / 60) + " min ago";
        }

        /// <summary>Whether the shared scene matches everyone's, with Check now and (for a drifted guest) Fix.</summary>
        private static void DrawSceneCheck()
        {
            if (!TeamScene.IsLive(TeamSession.ScenePath()))
                return;

            string text;
            Color color = WPFMAToolSection.MetaText;
            bool canFix = false;
            if (TeamSession.IsHost)
            {
                var parts = TeamSession.Peers.Where(p => p.Link != null && TeamScene.GuestCheck.ContainsKey(p.Id))
                    .Select(p => TeamScene.GuestCheck[p.Id].Length == 0 ? p.Name + " ✓" : p.Name + ": " + TeamScene.GuestCheck[p.Id]).ToList();
                bool anyOff = TeamSession.Peers.Any(p => TeamScene.GuestCheck.ContainsKey(p.Id) && TeamScene.GuestCheck[p.Id].Length > 0);
                if (TeamScene.CheckNote != null)
                    text = TeamScene.CheckNote;
                else if (parts.Count == 0)
                    text = "Scene check runs every few seconds while nobody is editing.";
                else
                    text = "Scene check (" + Ago(TeamScene.LastCheck) + "): " + string.Join("  ·  ", parts.ToArray());
                if (anyOff)
                    color = WPFMAToolSection.WarnAmber;
                else if (parts.Count > 0)
                    color = WPFMAToolSection.OkGreen;
            }
            else if (TeamScene.Fixing)
            {
                text = "Getting a fresh copy of the scene from " + (TeamSession.RemoteName ?? "the host") + "...";
                color = WPFMAToolSection.AccentBlue;
            }
            else if (TeamScene.DriftScene != null)
            {
                text = "Scene out of sync: " + string.Join(", ", TeamScene.DriftNames.ToArray()) +
                       (TeamScene.DriftCount > TeamScene.DriftNames.Count ? " and " + (TeamScene.DriftCount - TeamScene.DriftNames.Count) + " more" : string.Empty);
                color = WPFMAToolSection.WarnAmber;
                canFix = true;
            }
            else if (TeamScene.CheckNote != null)
            {
                text = TeamScene.CheckNote;
            }
            else if (TeamScene.LastCheck > 0)
            {
                text = "Scene matches " + (TeamSession.RemoteName ?? "the host") + "'s (checked " + Ago(TeamScene.LastCheck) + ")";
                color = WPFMAToolSection.OkGreen;
            }
            else
            {
                text = "Scene check runs every few seconds while nobody is editing.";
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField(text, Hint(color));
                if (canFix && GUILayout.Button(new GUIContent("Fix", "Get a fresh copy of the scene from the host"), EditorStyles.miniButton, GUILayout.Width(40f)))
                    EditorApplication.delayCall += TeamScene.FixNow;
                if (GUILayout.Button("Check now", EditorStyles.miniButton, GUILayout.Width(72f)))
                    TeamScene.CheckNow();
            }
        }

        /// <summary>One line: ready to upload, or what's still on its way and whose.</summary>
        private static void DrawReady()
        {
            var notReady = TeamSession.NotReady();
            if (notReady.Count == 0)
            {
                EditorGUILayout.LabelField("Ready to upload: everyone has everything", Hint(WPFMAToolSection.OkGreen));
                return;
            }
            string first = notReady[0] + (notReady.Count > 1 ? "  (+" + (notReady.Count - 1) + " more)" : string.Empty);
            EditorGUILayout.LabelField(new GUIContent("Not ready to upload yet: " + first, string.Join("\n", notReady.ToArray())), Hint(WPFMAToolSection.MetaText));
        }

        private static double sampleAt = -1;
        private static long sampleDone;
        private static double rate;

        /// <summary>"  ·  8.3 MB/s  ·  about 6 min left", smoothed so it doesn't jump around.</summary>
        private static string Speed()
        {
            double now = EditorApplication.timeSinceStartup;
            long done = TeamFiles.DownloadDone;
            if (sampleAt < 0 || done < sampleDone)
            {
                sampleAt = now;
                sampleDone = done;
            }
            else if (now - sampleAt >= 1.0)
            {
                double current = (done - sampleDone) / (now - sampleAt);
                rate = rate <= 0 ? current : rate * 0.7 + current * 0.3;
                sampleAt = now;
                sampleDone = done;
            }
            if (rate < 1024)
                return string.Empty;
            double left = (TeamFiles.DownloadTotal - done) / rate;
            string eta = left < 60 ? "under a minute left" : left < 3600 ? "about " + Math.Ceiling(left / 60) + " min left" : "about " + (left / 3600).ToString("0.#") + " h left";
            return "  ·  " + Size((long)rate) + "/s  ·  " + eta;
        }

        private static string Activity(TeamPeer peer)
        {
            if (peer.Busy)
                return "Their Unity is reloading...";
            if (peer.Playing)
                return "In Play mode";
            if (!string.IsNullOrEmpty(peer.Prefab))
                return "Editing the prefab " + Path.GetFileNameWithoutExtension(peer.Prefab);

            string where = string.IsNullOrEmpty(peer.Window) ? null : "In " + peer.Window;
            string what = string.IsNullOrEmpty(peer.Asset) ? null : Path.GetFileName(peer.Asset);
            string scene = string.IsNullOrEmpty(peer.ScenePath) ? null : Path.GetFileNameWithoutExtension(peer.ScenePath);
            var parts = new[] { where, what, scene != null && !TeamScene.IsLive(peer.ScenePath) ? "in scene " + scene : null }
                .Where(p => p != null).ToArray();
            return parts.Length == 0 ? "Connected" : string.Join("  ·  ", parts);
        }

        private static string SyncLine()
        {
            switch (TeamFiles.Phase)
            {
                case TeamSyncPhase.Scanning:
                    return TeamFiles.PhaseText ?? "Comparing projects...";
                case TeamSyncPhase.Review:
                case TeamSyncPhase.Downloading:
                    return "Getting " + (TeamSession.RemoteName ?? "the host") + "'s project...";
            }

            if (TeamScene.WaitingForScene)
                return TeamScene.Notice ?? "Opening the shared scene...";
            if (TeamFiles.SendingCount > 0)
                return "Sending " + TeamFiles.SendingCount + " file(s)" + (TeamFiles.SendingName != null ? " - " + Path.GetFileName(TeamFiles.SendingName) : string.Empty);
            if (TeamFiles.AwaitingCount > 0)
                return TeamFiles.AwaitingCount + " new file(s) on their way (marked ⇡); they can be placed once they arrive";

            string mine = TeamSession.ScenePath();
            return TeamScene.IsLive(mine)
                ? "Everything in sync  ·  editing " + Path.GetFileNameWithoutExtension(mine) + " together"
                : "Files in sync  ·  your open scene isn't shared";
        }

        private static Color SyncColor()
        {
            return TeamFiles.Phase == TeamSyncPhase.Live && TeamFiles.SendingCount == 0 && TeamFiles.AwaitingCount == 0 && TeamScene.IsLive(TeamSession.ScenePath())
                ? WPFMAToolSection.OkGreen
                : WPFMAToolSection.MetaText;
        }

        /// <summary>Only the things that actually need the user, one line each.</summary>
        private static void DrawNeedsYou(string name)
        {
            // Host: files a guest has that this project doesn't (asked for now and then).
            if (TeamSession.IsHost && TeamFiles.Phase == TeamSyncPhase.Live)
            {
                foreach (var peer in TeamSession.Peers.Where(p => p.Link != null && p.Up).ToList())
                {
                    TeamFiles.AskTheirFiles(peer);
                    var theirs = TeamFiles.MissingFrom(peer);
                    if (theirs.Count == 0)
                        continue;
                    using (new EditorGUILayout.HorizontalScope())
                    {
                        EditorGUILayout.LabelField(peer.Name + " has " + theirs.Count + " file(s) you don't (" + Size(theirs.Sum(f => f.Size)) + ")",
                            Hint(WPFMAToolSection.MetaText));
                        if (GUILayout.Button("See them", GUILayout.Width(80f)))
                        {
                            var target = peer;
                            EditorApplication.delayCall += () => TeamTheirFilesWindow.Open(target);
                        }
                    }
                }
            }

            // Only when "Get the host's project automatically" is off.
            if (TeamFiles.Phase == TeamSyncPhase.Review)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.LabelField("Match your project to " + name + "'s: " + (TeamFiles.ReviewNew + TeamFiles.ReviewChanged) + " file(s), " +
                                               Size(TeamFiles.ReviewBytes) + " (yours are backed up)", Hint(WPFMAToolSection.WarnAmber));
                    if (GUILayout.Button("Get it", GUILayout.Width(60f)))
                        EditorApplication.delayCall += TeamFiles.StartDownload;
                }
            }

            // Teammates working in another scene: Join opens it and you edit it together (opening it yourself does too).
            foreach (var peer in TeamSession.Peers.ToList())
            {
                string theirs = peer.ScenePath;
                if (string.IsNullOrEmpty(theirs) || TeamScene.IsLive(theirs) || TeamScene.WaitingForScene || peer.Playing ||
                    !string.IsNullOrEmpty(peer.Prefab) || TeamFiles.Phase != TeamSyncPhase.Live)
                    continue;
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.LabelField(new GUIContent(peer.Name + " is working in " + Path.GetFileNameWithoutExtension(theirs), theirs), Hint(WPFMAToolSection.MetaText));
                    if (GUILayout.Button(new GUIContent("Join", "Open " + Path.GetFileNameWithoutExtension(theirs) + " and edit it with " + peer.Name), GUILayout.Width(60f)))
                    {
                        var target = peer;
                        EditorApplication.delayCall += () => TeamScene.JoinPeer(target);
                    }
                }
            }

            // Scripts waiting because trust is off.
            if (TeamFiles.Pending.Count > 0)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.LabelField(TeamFiles.Pending.Count + " script(s) from " + name + " are waiting for you", Hint(WPFMAToolSection.WarnAmber));
                    if (GUILayout.Button("Look", GUILayout.Width(50f)))
                        TeamCodeView.Show(TeamFiles.Pending[0]);
                    if (GUILayout.Button("Allow all", GUILayout.Width(70f)))
                        TeamFiles.AcceptAll();
                }
            }

            // Paid things to get yourself, and installs in progress.
            bool anyShown = false;
            foreach (var item in TeamProject.Hidden ? Enumerable.Empty<TeamMissing>() : TeamProject.Missing.ToList())
            {
                string status;
                bool installing = TeamProject.InstallStatus.TryGetValue(item.Name, out status);
                if (TeamProject.CanInstall(item) && !installing)
                    continue;
                anyShown = true;
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.LabelField(installing ? item.Name + ": " + status : "Needs " + item.Name + (item.Kind == "Shader" ? " (shader)" : string.Empty),
                        Hint(installing ? WPFMAToolSection.AccentBlue : WPFMAToolSection.WarnAmber));
                    if (!installing && !string.IsNullOrEmpty(item.Url) && GUILayout.Button("Get it", GUILayout.Width(60f)))
                        Application.OpenURL(item.Url);
                }
            }
            if (anyShown && GUILayout.Button("I have these, hide", EditorStyles.miniButton, GUILayout.Width(120f)))
                TeamProject.Hidden = true;
            if (TeamProject.ArrivingShaders > 0 && TeamFiles.Phase == TeamSyncPhase.Live)
                EditorGUILayout.LabelField(TeamProject.ArrivingShaders + " shader(s) from the project are still on their way.", Hint(WPFMAToolSection.FaintText));
            foreach (var warning in TeamProject.Warnings)
                EditorGUILayout.LabelField(warning, Hint(WPFMAToolSection.WarnAmber));

            foreach (var peer in TeamSession.Peers.Where(p => TeamSession.Now - p.UploadAt < 180).ToList())
                EditorGUILayout.LabelField(peer.Name + " is building or uploading; wait for them before uploading yourself.", Hint(WPFMAToolSection.WarnAmber));

            if (!string.IsNullOrEmpty(TeamFiles.CheckResult) && !TeamFiles.CheckResult.StartsWith("Everything matches"))
                EditorGUILayout.LabelField(TeamFiles.CheckResult, Hint(WPFMAToolSection.WarnAmber));
            else if (!string.IsNullOrEmpty(TeamFiles.CheckResult))
                EditorGUILayout.LabelField(TeamFiles.CheckResult, Hint(WPFMAToolSection.OkGreen));
        }

        // ---- Chat ---------------------------------------------------------------------------------------------------

        private static void DrawChat()
        {
            if (TeamSession.Chat.Count == 0 && TeamSession.State != TeamState.Connected)
                return;

            EditorGUILayout.Space(8f);
            if (TeamSession.Chat.Count != lastChatCount)
            {
                lastChatCount = TeamSession.Chat.Count;
                chatScroll.y = float.MaxValue;
            }

            chatScroll = EditorGUILayout.BeginScrollView(chatScroll, GUILayout.Height(170f));
            foreach (var line in TeamSession.Chat)
            {
                if (line.System)
                {
                    EditorGUILayout.LabelField(line.Time + "  " + line.Text, Hint(WPFMAToolSection.FaintText));
                    continue;
                }

                var color = line.Mine ? TeamSession.LocalColor : (line.Color.a > 0 ? line.Color : TeamSession.RemoteColor);
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.LabelField(line.Name + ":", new GUIStyle(EditorStyles.miniBoldLabel) { normal = { textColor = color } }, GUILayout.Width(90f));
                    EditorGUILayout.LabelField(line.Text, new GUIStyle(EditorStyles.wordWrappedMiniLabel) { normal = { textColor = WPFMAToolSection.MetaText } });
                }
            }
            EditorGUILayout.EndScrollView();

            using (new EditorGUI.DisabledScope(TeamSession.State != TeamState.Connected))
            using (new EditorGUILayout.HorizontalScope())
            {
                bool send = Event.current.type == EventType.KeyDown &&
                            (Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.KeypadEnter) &&
                            GUI.GetNameOfFocusedControl() == "WPFMATeamChat";

                GUI.SetNextControlName("WPFMATeamChat");
                chatInput = EditorGUILayout.TextField(chatInput);
                if (GUILayout.Button("Send", GUILayout.Width(60f)) || send)
                {
                    if (send)
                        Event.current.Use();
                    TeamSession.SendChat(chatInput);
                    chatInput = string.Empty;
                    GUI.FocusControl("WPFMATeamChat");
                }
            }
            EditorGUILayout.LabelField("Alt+G pings where you're looking.", Hint(WPFMAToolSection.FaintText));
        }

        private static string Size(long bytes)
        {
            if (bytes >= 1024L * 1024 * 1024)
                return (bytes / (1024.0 * 1024 * 1024)).ToString("0.0") + " GB";
            if (bytes >= 1024 * 1024)
                return (bytes / (1024.0 * 1024)).ToString("0.0") + " MB";
            return Math.Max(1, bytes / 1024) + " KB";
        }
    }
}
#endif
