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

namespace WPFMA.Team
{
    /// <summary>
    /// Team doctor: one window that checks everything a session depends on - the port, reaching reqid.io, what kind
    /// of router you're behind, whether it opens ports by itself, Tailscale - and, during a session, each teammate's
    /// connection, versions, packages, layers and whether the scene matches. Each problem comes with what to do, and
    /// a button where Team can do it for you. "Copy report" gives a text version to paste when asking for help.
    /// </summary>
    internal sealed class TeamDoctor : EditorWindow
    {
        private enum Mark
        {
            Ok,
            Warn,
            Bad,
            Info,
            Running
        }

        private sealed class Row
        {
            public string Group;
            public Mark Mark;
            public string Title;
            public string Detail;
            public string Button;
            public Action Run;
        }

        private sealed class StunResult
        {
            public IPEndPoint First;
            public IPEndPoint Second;
        }

        private readonly List<Row> rows = new List<Row>();
        private Vector2 scroll;
        private Task<string> serverTask;
        private Stopwatch serverClock;
        private Task<StunResult> stunTask;
        private Task<bool> upnpTask;
        private Row serverRow;
        private Row stunRow;
        private Row upnpRow;

        internal static void Open()
        {
            var window = GetWindow<TeamDoctor>(true, "Team doctor", true);
            window.minSize = new Vector2(480f, 420f);
            window.RunChecks();
        }

        private void OnEnable()
        {
            if (rows.Count == 0)
                RunChecks();
        }

        private static Color MarkColor(Mark mark)
        {
            switch (mark)
            {
                case Mark.Ok: return WPFMAToolSection.OkGreen;
                case Mark.Warn: return WPFMAToolSection.WarnAmber;
                case Mark.Bad: return new Color(0.95f, 0.38f, 0.35f);
                case Mark.Running: return WPFMAToolSection.AccentBlue;
                default: return WPFMAToolSection.MetaText;
            }
        }

        private static string MarkText(Mark mark)
        {
            switch (mark)
            {
                case Mark.Ok: return "✓";
                case Mark.Warn: return "!";
                case Mark.Bad: return "✗";
                case Mark.Running: return "…";
                default: return "i";
            }
        }

        private Row Add(string group, Mark mark, string title, string detail = null, string button = null, Action run = null)
        {
            var row = new Row { Group = group, Mark = mark, Title = title, Detail = detail, Button = button, Run = run };
            rows.Add(row);
            return row;
        }

        // ---- Checks -------------------------------------------------------------------------------------------------

        private void RunChecks()
        {
            rows.Clear();
            bool idle = TeamSession.State == TeamState.Idle;

            Add("This PC", Mark.Info, "WPFMA-SDK " + TeamPacket.SdkVersion + "  ·  Team " + TeamPacket.Protocol + "  ·  Unity " + Application.unityVersion,
                "Everyone in a session needs the same WPFMA-SDK version.");

            if (TeamSession.DisplayName == "Creator")
                Add("This PC", Mark.Warn, "You haven't set a name", "Teammates will see you as \"Creator\".", "Set name",
                    () => TeamSetupWindow.Open(TeamSetupWindow.Mode.Settings));

            CheckPort(idle);
            CheckNetwork();

            serverRow = Add("Internet", Mark.Running, "Reaching reqid.io (where sessions meet)...");
            serverClock = Stopwatch.StartNew();
            serverTask = TeamHttp.Post("/api/team-poll.php", new Dictionary<string, string> { { "code", "DOCTOR" }, { "secret", "doctor" } });

            stunRow = Add("Internet", Mark.Running, "Finding your internet address and router type...");
            stunTask = Task.Run(() => Stun());

            if (idle)
            {
                upnpRow = Add("Internet", Mark.Running, "Asking your router whether it opens ports by itself...");
                int port = TeamSession.Port;
                string ip = TeamAddress.LocalIp();
                upnpTask = ip == null ? Task.FromResult(false) : Task.Run(() =>
                {
                    var mapping = TeamUpnp.TryOpen(port, ip);
                    if (mapping == null)
                        return false;
                    TeamUpnp.Close(mapping);
                    return true;
                });
            }
            else
            {
                upnpTask = null;
                upnpRow = null;
            }

            if (Application.platform == RuntimePlatform.WindowsEditor)
                Add("Internet", Mark.Info, "Windows Firewall",
                    "If friends can't reach you, allow Unity through the firewall for Private and Public networks.",
                    "Open firewall", OpenFirewall);

            if (TeamSession.State == TeamState.Connected)
                CheckSession();
            else if (!idle)
                Add("Session", Mark.Running, "Connecting... (" + (TeamSession.Status ?? "") + ")", "Run the checks again once connected to check teammates too.");
            else if (!string.IsNullOrEmpty(TeamSession.Error))
                Add("Session", Mark.Bad, "Last attempt failed", TeamSession.Error);

            Repaint();
        }

        private void CheckPort(bool idle)
        {
            int port = TeamSession.Port;
            if (!idle)
            {
                if (TeamSession.BoundPort == port)
                    Add("This PC", Mark.Ok, "Using port " + port);
                else
                    Add("This PC", Mark.Warn, "Port " + port + " was busy, so Team used " + TeamSession.BoundPort,
                        "Fine for joining. If you host, friends using 'Join by address' need port " + TeamSession.BoundPort + ".");
                return;
            }

            if (PortFree(port))
            {
                Add("This PC", Mark.Ok, "Port " + port + " is free");
                return;
            }
            Add("This PC", Mark.Bad, "Port " + port + " is used by another program",
                "Another Unity with Team open, or another app. Team would pick a random port, which friends can't guess.",
                "Use a free port", () =>
                {
                    for (int candidate = 47321; candidate < 47400; candidate++)
                    {
                        if (!PortFree(candidate))
                            continue;
                        TeamSession.Port = candidate;
                        break;
                    }
                    RunChecks();
                });
        }

        private static bool PortFree(int port)
        {
            try
            {
                using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                    socket.Bind(new IPEndPoint(IPAddress.Any, port));
                return true;
            }
            catch (SocketException)
            {
                return false;
            }
        }

        private void CheckNetwork()
        {
            string local = TeamAddress.LocalIp();
            if (local == null)
            {
                Add("This PC", Mark.Bad, "No network connection found", "Connect to the internet (or your home network) first.");
                return;
            }
            Add("This PC", Mark.Info, "Home network address " + local);

            string tailscale = TailscaleAddress();
            if (tailscale != null)
            {
                string address = tailscale + ":" + TeamSession.Port;
                Add("This PC", Mark.Ok, "Tailscale is on: " + tailscale,
                    "If connecting over the internet fails, friends on your Tailscale can use 'Join by address' with " + address + ".",
                    "Copy address", () => EditorGUIUtility.systemCopyBuffer = address);
            }
            else
            {
                Add("This PC", Mark.Info, "Tailscale isn't running", "Only needed when connecting directly fails for you and a friend.");
            }
        }

        private static string TailscaleAddress()
        {
            try
            {
                foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (adapter.OperationalStatus != OperationalStatus.Up)
                        continue;
                    foreach (var unicast in adapter.GetIPProperties().UnicastAddresses)
                    {
                        var b = unicast.Address.GetAddressBytes();
                        if (unicast.Address.AddressFamily == AddressFamily.InterNetwork && b[0] == 100 && b[1] >= 64 && b[1] <= 127)
                            return unicast.Address.ToString();
                    }
                }
            }
            catch (Exception)
            {
            }
            return null;
        }

        /// <summary>Asks two STUN servers what our address looks like from outside, from the same socket.</summary>
        private static StunResult Stun()
        {
            var result = new StunResult();
            var servers = TeamStun.Servers.Select(TeamAddress.Parse).Where(e => e != null).ToList();
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                socket.Bind(new IPEndPoint(IPAddress.Any, 0));
                socket.ReceiveTimeout = 1500;
                var seenHosts = new HashSet<string>();
                foreach (var server in servers)
                {
                    // Two different servers (different addresses) show whether the router keeps one port for everyone.
                    if (!seenHosts.Add(server.Address.ToString()))
                        continue;
                    byte[] transaction;
                    var request = TeamStun.Request(out transaction);
                    IPEndPoint mapped = null;
                    for (int attempt = 0; attempt < 2 && mapped == null; attempt++)
                    {
                        try
                        {
                            socket.SendTo(request, server);
                            var buffer = new byte[1024];
                            EndPoint from = new IPEndPoint(IPAddress.Any, 0);
                            int length = socket.ReceiveFrom(buffer, ref from);
                            mapped = TeamStun.ParseResponse(buffer, length, transaction);
                        }
                        catch (SocketException)
                        {
                        }
                    }
                    if (mapped == null)
                        continue;
                    if (result.First == null)
                        result.First = mapped;
                    else
                    {
                        result.Second = mapped;
                        break;
                    }
                }
            }
            return result;
        }

        private void CheckSession()
        {
            foreach (var peer in TeamSession.Peers)
            {
                string who = peer.Name + (peer.IsHost ? " (host)" : string.Empty);
                if (peer.Link == null)
                {
                    Add("Teammates", Mark.Info, who, "Connected through the host.");
                    continue;
                }
                if (!peer.Up)
                {
                    Add("Teammates", Mark.Warn, who + ": reconnecting", "Their connection dropped for a moment; Team keeps trying.");
                    continue;
                }
                if (peer.Busy)
                {
                    Add("Teammates", Mark.Info, who + ": their Unity is reloading");
                    continue;
                }
                int ping = peer.PingMs;
                if (ping < 0)
                    Add("Teammates", Mark.Info, who + ": connected");
                else if (ping < 120)
                    Add("Teammates", Mark.Ok, who + ": " + ping + " ms");
                else if (ping < 300)
                    Add("Teammates", Mark.Warn, who + ": " + ping + " ms (slow)", "Edits still sync, just with a delay. Big file transfers take longer.");
                else
                    Add("Teammates", Mark.Bad, who + ": " + ping + " ms (very slow)",
                        "Someone's internet is struggling (downloads or streams running?). Closing those helps.");
            }

            foreach (var warning in TeamProject.Warnings)
                Add("Project", Mark.Warn, warning);
            if (TeamProject.LayersDiffer && !TeamSession.IsHost)
                Add("Project", Mark.Warn, "Your layers and tags differ from the host's", "Objects can end up on the wrong layer (mirrors, colliders).",
                    "Use the host's", () =>
                    {
                        TeamProject.UseRemoteLayersAndTags();
                        RunChecks();
                    });
            int missing = TeamProject.Missing.Count;
            if (missing > 0)
                Add("Project", Mark.Warn, missing + " package(s) or shader(s) you don't have",
                    string.Join(", ", TeamProject.Missing.Take(4).Select(m => m.Name).ToArray()) + (missing > 4 ? "..." : string.Empty) +
                    ". The Team tab lists them with links.");
            if (TeamProject.Warnings.Count == 0 && !TeamProject.LayersDiffer && missing == 0)
                Add("Project", Mark.Ok, "Unity, packages and layers match");

            if (TeamFiles.Pending.Count > 0)
                Add("Project", Mark.Warn, TeamFiles.Pending.Count + " script(s) waiting for 'Trust code'", "Check them in the Team tab.");

            if (TeamScene.IsLive(TeamSession.ScenePath()))
            {
                if (TeamScene.DriftScene != null)
                    Add("Scene", Mark.Warn, "Scene out of sync: " + string.Join(", ", TeamScene.DriftNames.ToArray()), null,
                        TeamScene.Fixing ? null : "Fix", () =>
                        {
                            TeamScene.FixNow();
                            RunChecks();
                        });
                else
                {
                    var off = TeamSession.Peers.Where(p => TeamScene.GuestCheck.ContainsKey(p.Id) && TeamScene.GuestCheck[p.Id].Length > 0).ToList();
                    if (off.Count > 0)
                        foreach (var peer in off)
                            Add("Scene", Mark.Warn, peer.Name + "'s scene: " + TeamScene.GuestCheck[peer.Id]);
                    else
                        Add("Scene", Mark.Ok, "Shared scene matches" + (TeamScene.LastCheck > 0 ? "" : " (not checked yet)"), null,
                            "Check now", TeamScene.CheckNow);
                }
            }
            else
            {
                Add("Scene", Mark.Info, "Your open scene isn't shared", "Open the scene your teammates are in to edit together.");
            }

            var notReady = TeamSession.NotReady();
            if (notReady.Count == 0)
                Add("Upload", Mark.Ok, "Ready to upload: everyone has everything");
            else
                Add("Upload", Mark.Warn, "Not ready to upload yet", string.Join("\n", notReady.ToArray()));
        }

        private static void OpenFirewall()
        {
            try
            {
                Process.Start(new ProcessStartInfo("control.exe", "/name Microsoft.WindowsFirewall /page pageConfigureApps") { UseShellExecute = true });
            }
            catch (Exception)
            {
                Application.OpenURL("https://support.microsoft.com/windows/risks-of-allowing-apps-through-windows-firewall-654559af-3f54-3dcf-349f-71ccd90bcc5c");
            }
        }

        // ---- Results arriving -----------------------------------------------------------------------------------

        private void Update()
        {
            bool changed = false;

            if (serverTask != null && serverTask.IsCompleted)
            {
                long ms = serverClock != null ? serverClock.ElapsedMilliseconds : 0;
                if (serverTask.Status == TaskStatus.RanToCompletion)
                {
                    TeamReply reply = null;
                    try
                    {
                        reply = JsonUtility.FromJson<TeamReply>(serverTask.Result);
                    }
                    catch (Exception)
                    {
                    }
                    if (reply != null && (reply.ok || !string.IsNullOrEmpty(reply.error)))
                        Set(serverRow, Mark.Ok, "reqid.io is reachable (" + ms + " ms)");
                    else
                        Set(serverRow, Mark.Warn, "reqid.io answered strangely", "A proxy or filter on your network may be changing web traffic.");
                }
                else
                {
                    string why = serverTask.Exception != null ? serverTask.Exception.GetBaseException().Message : "no answer";
                    Set(serverRow, Mark.Bad, "Can't reach reqid.io", why + ". Your internet, a firewall or an ad blocker may block it. You can still host " +
                        "without the website and have friends use 'Join by address' (same network, or Tailscale).");
                }
                serverTask = null;
                changed = true;
            }

            if (stunTask != null && stunTask.IsCompleted)
            {
                var result = stunTask.Status == TaskStatus.RanToCompletion ? stunTask.Result : null;
                if (result == null || result.First == null)
                    Set(stunRow, Mark.Warn, "Couldn't find your internet address",
                        "Something blocks the address lookup (STUN). Joining over the internet may fail; Tailscale works around it.",
                        "Get Tailscale", () => Application.OpenURL("https://tailscale.com/download"));
                else if (result.Second == null || result.Second.Port == result.First.Port)
                    Set(stunRow, Mark.Ok, "Internet address " + result.First.Address + ": your router is friendly",
                        "It keeps one port for everyone, so direct connections should work.");
                else
                    Set(stunRow, Mark.Warn, "Your router gives each connection its own port",
                        "Direct connections can fail if your friend's router does this too. Team tries hard anyway; if it keeps failing, " +
                        "both install Tailscale (free) and use 'Join by address'.",
                        "Get Tailscale", () => Application.OpenURL("https://tailscale.com/download"));
                stunTask = null;
                changed = true;
            }

            if (upnpTask != null && upnpTask.IsCompleted)
            {
                bool opened = upnpTask.Status == TaskStatus.RanToCompletion && upnpTask.Result;
                if (opened)
                    Set(upnpRow, Mark.Ok, "Your router opens ports by itself (UPnP)", "That makes connecting easier.");
                else
                    Set(upnpRow, Mark.Info, "Your router didn't open a port by itself",
                        "UPnP is off or not supported. That's fine when the router check above is green.");
                upnpTask = null;
                changed = true;
            }

            if (changed)
                Repaint();
        }

        private static void Set(Row row, Mark mark, string title, string detail = null, string button = null, Action run = null)
        {
            if (row == null)
                return;
            row.Mark = mark;
            row.Title = title;
            row.Detail = detail;
            row.Button = button;
            row.Run = run;
        }

        // ---- Drawing --------------------------------------------------------------------------------------------

        private void OnGUI()
        {
            EditorGUILayout.Space(6f);
            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.Space(8f);
                EditorGUILayout.LabelField("Team doctor", new GUIStyle(EditorStyles.boldLabel) { fontSize = 14 });
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Copy report", GUILayout.Width(90f)))
                    EditorGUIUtility.systemCopyBuffer = Report();
                if (GUILayout.Button("Run again", GUILayout.Width(80f)))
                    RunChecks();
                GUILayout.Space(8f);
            }
            EditorGUILayout.Space(4f);

            var title = new GUIStyle(EditorStyles.boldLabel) { wordWrap = true };
            var detail = new GUIStyle(EditorStyles.wordWrappedMiniLabel) { normal = { textColor = WPFMAToolSection.MetaText } };
            var groupStyle = new GUIStyle(EditorStyles.miniBoldLabel) { normal = { textColor = WPFMAToolSection.FaintText } };

            scroll = EditorGUILayout.BeginScrollView(scroll);
            string group = null;
            foreach (var row in rows.ToList())
            {
                if (row.Group != group)
                {
                    group = row.Group;
                    EditorGUILayout.Space(6f);
                    using (new EditorGUILayout.HorizontalScope())
                    {
                        GUILayout.Space(10f);
                        EditorGUILayout.LabelField(group.ToUpperInvariant(), groupStyle);
                    }
                }
                using (new EditorGUILayout.HorizontalScope())
                {
                    GUILayout.Space(10f);
                    var markStyle = new GUIStyle(EditorStyles.boldLabel) { normal = { textColor = MarkColor(row.Mark) }, alignment = TextAnchor.UpperCenter };
                    GUILayout.Label(MarkText(row.Mark), markStyle, GUILayout.Width(16f));
                    using (new EditorGUILayout.VerticalScope())
                    {
                        EditorGUILayout.LabelField(row.Title, title);
                        if (!string.IsNullOrEmpty(row.Detail))
                            EditorGUILayout.LabelField(row.Detail, detail);
                    }
                    if (!string.IsNullOrEmpty(row.Button) && row.Run != null)
                    {
                        var run = row.Run;
                        if (GUILayout.Button(row.Button, EditorStyles.miniButton, GUILayout.Width(100f)))
                            EditorApplication.delayCall += () => run();
                    }
                    GUILayout.Space(8f);
                }
            }
            EditorGUILayout.Space(8f);
            EditorGUILayout.EndScrollView();
        }

        /// <summary>Plain text for pasting into a help request. Addresses are left out on purpose.</summary>
        private string Report()
        {
            var text = new StringBuilder("WPFMA Team doctor  " + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "\n");
            string group = null;
            foreach (var row in rows)
            {
                if (row.Group != group)
                {
                    group = row.Group;
                    text.Append('\n').Append(group).Append('\n');
                }
                string line = row.Title;
                if (row.Title.StartsWith("Home network address", StringComparison.Ordinal) || row.Title.StartsWith("Internet address", StringComparison.Ordinal))
                    line = row.Title.StartsWith("Internet") ? "Internet address found: your router is friendly" : "Home network address found";
                if (row.Title.StartsWith("Tailscale is on", StringComparison.Ordinal))
                    line = "Tailscale is on";
                text.Append("  [").Append(MarkText(row.Mark)).Append("] ").Append(line).Append('\n');
                if (!string.IsNullOrEmpty(row.Detail) && row.Group != "This PC")
                    text.Append("      ").Append(row.Detail.Replace("\n", "\n      ")).Append('\n');
            }
            return text.ToString();
        }
    }
}
#endif
