// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using UnityEditor;

namespace WPFMA.Team
{
    /// <summary>
    /// Two things that keep a session smooth:
    ///
    /// Ready to upload - every editor shares a short "what's still on its way" note (files being sent or waited for,
    /// scene changes not applied yet, Play mode, a scene that drifted). Before an upload, anything that isn't done is
    /// listed, so nobody uploads a world that's missing a teammate's last changes.
    ///
    /// Host handoff - the host can pass the session to a guest without anyone losing it. The invite on reqid.io is
    /// owned by its code and secret, and each host check-in updates the host's address there, so the old host hands
    /// the new host the code and secret over the (encrypted) Team link. The new host takes the same invite over and
    /// everyone else, the old host included, rejoins the same code a few seconds apart. No server change needed.
    /// </summary>
    internal static partial class TeamSession
    {
        // ---- Ready to upload ----------------------------------------------------------------------------------------

        private static string lastStateSent;
        private static double lastStateAt = -100;

        /// <summary>What this editor still has on its way, one short line each. Empty when everything is done.</summary>
        internal static List<string> LocalPending()
        {
            var list = new List<string>();
            if (State != TeamState.Connected)
                return list;

            if (TeamFiles.Phase != TeamSyncPhase.Live)
                list.Add("still getting the project in sync");
            if (TeamFiles.SendingCount > 0)
                list.Add("sending " + Count(TeamFiles.SendingCount, "file"));
            if (TeamFiles.AwaitingCount > 0)
                list.Add("waiting for " + Count(TeamFiles.AwaitingCount, "file"));
            if (TeamFiles.Pending.Count > 0)
                list.Add(Count(TeamFiles.Pending.Count, "script") + " waiting for 'Trust code'");
            if (TeamScene.PendingCount > 0)
                list.Add(Count(TeamScene.PendingCount, "scene change") + " not sent or applied yet");
            if (EditorApplication.isPlayingOrWillChangePlaymode)
                list.Add("in Play mode (teammates' changes wait until it stops)");
            if (TeamScene.DriftScene != null)
                list.Add("scene out of sync" + (TeamScene.Fixing ? " (fixing)" : string.Empty));
            return list;
        }

        private static string Count(int n, string thing)
        {
            return n + " " + thing + (n == 1 ? string.Empty : "s");
        }

        /// <summary>Shares LocalPending when it changes (and now and then, in case a message was missed).</summary>
        private static void SendState()
        {
            if (Now - lastStateAt < 1.0)
                return;
            string text = string.Join("; ", LocalPending().ToArray());
            if (text == lastStateSent && Now - lastStateAt < 15.0)
                return;
            lastStateAt = Now;
            lastStateSent = text;
            Send(new TeamMessage { t = "state", m = text });
        }

        private static void ReceiveState(TeamPeer origin, TeamMessage message)
        {
            origin.Pending = message.m ?? string.Empty;
            Raise();
        }

        /// <summary>Everyone who isn't ready to upload yet, as "Name: what's left". Empty when everyone is synced.</summary>
        internal static List<string> NotReady()
        {
            var list = new List<string>();
            var mine = LocalPending();
            if (mine.Count > 0)
                list.Add("You: " + string.Join(", ", mine.ToArray()));
            foreach (var peer in Peers)
            {
                if (peer.Link != null && !peer.Up)
                    list.Add(peer.Name + ": reconnecting");
                else if (peer.Busy)
                    list.Add(peer.Name + ": their Unity is reloading");
                else if (!string.IsNullOrEmpty(peer.Pending))
                    list.Add(peer.Name + ": " + peer.Pending.Replace("; ", ", "));
            }
            if (Backlog > 0)
                list.Add("Still sending " + (Backlog / 1024 + 1) + " KB to teammates");
            return list;
        }

        // ---- Host handoff -------------------------------------------------------------------------------------------

        private sealed class Takeover
        {
            public string Secret;
            public string PeerKey;
            public long HandledGuestAt;
        }

        private sealed class Scheduled
        {
            public double At;
            public Action Run;
        }

        private static readonly List<Scheduled> scheduled = new List<Scheduled>();
        private static Takeover takeover;
        private static bool handingOff;
        private static IPEndPoint handoffHint;

        // The new host needs a few seconds to find its internet address and claim the invite; then the others
        // rejoin one at a time, since the invite holds one joiner at a time.
        private const double FirstRejoin = 6.0;
        private const double RejoinGap = 5.0;

        /// <summary>Handoff needs the reqid.io invite (not "host without the website") and a guest to hand to.</summary>
        internal static bool CanHandOff
        {
            get { return IsHost && State == TeamState.Connected && !string.IsNullOrEmpty(secret) && !string.IsNullOrEmpty(Code) && !handingOff; }
        }

        internal static bool HandingOff
        {
            get { return handingOff; }
        }

        /// <summary>Shown in the Team tab while waiting to rejoin after a handoff (null otherwise).</summary>
        internal static string RejoinNote { get; private set; }

        internal static void CancelRejoin()
        {
            scheduled.Clear();
            EditorPrefs.DeleteKey(PendingRejoinKey + ProjectKey);
            RejoinNote = null;
            Raise();
        }

        // ---- Rejoining that survives a script reload (or Unity being closed and opened) ---------------------------

        [Serializable]
        private sealed class PendingRejoin
        {
            public string code;
            public string password;
            public string hint;
            public string note;
            public long joinAt;
            public int attempts;
        }

        // The new host may need longer than planned (its Unity reloaded, a slow connection): try again a few times.
        private const int RejoinAttempts = 5;
        private const double RejoinRetry = 5.0;

        private const string PendingRejoinKey = "WPFMA.Team.PendingRejoin.";

        // A rejoin that was due more than this long ago is stale (the session has moved on).
        private const double PendingRejoinLimit = 180.0;

        /// <summary>Rejoins this code after a delay. Saved to disk first, so a reload in between doesn't lose it.</summary>
        private static void ScheduleRejoin(double seconds, string code, string pwd, IPEndPoint hint, string note)
        {
            var record = new PendingRejoin
            {
                code = code,
                password = pwd ?? string.Empty,
                hint = hint != null ? TeamAddress.Format(hint) : string.Empty,
                note = note,
                joinAt = DateTime.UtcNow.AddSeconds(seconds).Ticks
            };
            EditorPrefs.SetString(PendingRejoinKey + ProjectKey, UnityEngine.JsonUtility.ToJson(record));
            RejoinNote = note;
            Schedule(seconds, RunRejoin);
        }

        private static PendingRejoin ReadPendingRejoin()
        {
            string json = EditorPrefs.GetString(PendingRejoinKey + ProjectKey, string.Empty);
            if (string.IsNullOrEmpty(json))
                return null;
            try
            {
                return UnityEngine.JsonUtility.FromJson<PendingRejoin>(json);
            }
            catch (Exception)
            {
                return null;
            }
        }

        // The record stays on disk until the rejoin connects (or runs out of tries), so a reload mid-join resumes it.
        private static void RunRejoin()
        {
            var record = ReadPendingRejoin();
            RejoinNote = null;
            if (record == null || string.IsNullOrEmpty(record.code) || State != TeamState.Idle)
            {
                Raise();
                return;
            }
            handoffHint = TeamAddress.Parse(record.hint);
            Join(record.code, record.password);
        }

        /// <summary>Connected again after a handoff: nothing left to resume.</summary>
        private static void RejoinDone()
        {
            EditorPrefs.DeleteKey(PendingRejoinKey + ProjectKey);
            RejoinNote = null;
        }

        /// <summary>A handoff rejoin failed (the new host wasn't ready yet): try again shortly, a few times.</summary>
        private static void RetryRejoin()
        {
            var record = ReadPendingRejoin();
            if (record == null)
                return;
            if (++record.attempts >= RejoinAttempts)
            {
                RejoinDone();
                return;
            }
            record.joinAt = DateTime.UtcNow.AddSeconds(RejoinRetry).Ticks;
            EditorPrefs.SetString(PendingRejoinKey + ProjectKey, UnityEngine.JsonUtility.ToJson(record));
            RejoinNote = record.note + " (trying again)";
            Schedule(RejoinRetry, RunRejoin);
        }

        /// <summary>After a reload or restart: pick a handoff rejoin back up where it was.</summary>
        private static bool RestorePendingRejoin()
        {
            var record = ReadPendingRejoin();
            if (record == null)
                return false;
            double wait = (new DateTime(record.joinAt, DateTimeKind.Utc) - DateTime.UtcNow).TotalSeconds;
            if (wait < -PendingRejoinLimit || string.IsNullOrEmpty(record.code))
            {
                EditorPrefs.DeleteKey(PendingRejoinKey + ProjectKey);
                return false;
            }
            RejoinNote = record.note;
            Schedule(Math.Max(0.5, wait), RunRejoin);
            Raise();
            return true;
        }

        private static void Schedule(double seconds, Action run)
        {
            scheduled.Add(new Scheduled { At = Now + seconds, Run = run });
        }

        // Runs even while not in a session (between leaving and rejoining).
        private static void RunScheduled()
        {
            if (scheduled.Count == 0)
                return;
            foreach (var item in scheduled.Where(s => Now >= s.At).ToList())
            {
                scheduled.Remove(item);
                try
                {
                    item.Run();
                }
                catch (Exception e)
                {
                    UnityEngine.Debug.LogException(e);
                }
            }
        }

        /// <summary>Host: makes this guest the host. Everyone else, you included, reconnects to them on its own.</summary>
        internal static void HandOff(TeamPeer to)
        {
            if (!CanHandOff || to == null || to.Link == null || !to.Up)
                return;

            handingOff = true;
            string code = Code;
            string pwd = password;
            var hint = to.Remote;
            var others = Peers.Where(p => p.Link != null && p != to).ToList();

            SendTo(to, new TeamMessage { t = "handoff", code = code, key = secret, json = peerKey ?? string.Empty, ts = handledGuestAt });
            for (int i = 0; i < others.Count; i++)
                SendTo(others[i], new TeamMessage
                {
                    t = "newhost", m = to.Id, name = to.Name, code = code, n = i,
                    f = hint != null ? TeamAddress.Format(hint) : string.Empty
                });

            AddSystem("Handing the session to " + to.Name + ". Everyone reconnects to them in a few seconds, you too.");
            Raise();

            // Leave once the handoff messages are delivered (or after a few seconds), keeping the invite open for them.
            // A second more after delivery, so nobody handles our goodbye before the handoff message itself.
            double started = Now;
            double sentAt = -1;
            Action leaveWhenSent = null;
            leaveWhenSent = () =>
            {
                if (Backlog > 0 && Now - started < 4.0)
                {
                    Schedule(0.25, leaveWhenSent);
                    return;
                }
                if (sentAt < 0)
                    sentAt = Now;
                if (Now - sentAt < 1.0 && Peers.Any(p => p.Link != null))
                {
                    Schedule(0.25, leaveWhenSent);
                    return;
                }
                Leave(null, true, true);
                Raise();
            };
            Schedule(0.5, leaveWhenSent);

            ScheduleRejoin(FirstRejoin + RejoinGap * others.Count, code, pwd, hint, "Reconnecting to " + to.Name + " as a guest...");
        }

        /// <summary>Guest: the host handed the session to us. Take the invite over and wait for everyone.</summary>
        private static void OnHandoff(TeamPeer from, TeamMessage message)
        {
            if (IsHost || from == null || !from.IsHost || string.IsNullOrEmpty(message.code) || string.IsNullOrEmpty(message.key))
                return;

            string code = message.code;
            string pwd = password;
            var data = new Takeover { Secret = message.key, PeerKey = message.json, HandledGuestAt = (long)message.ts };
            string oldHost = from.Name;

            Leave(null, true);
            Reset();
            ClearModules();
            IsHost = true;
            password = pwd;
            Code = code;
            takeover = data;
            Prepare();
            AddSystem(oldHost + " made you the host. Everyone is reconnecting to you.");
            Raise();
        }

        /// <summary>Guest: someone else is the host now. Leave, then rejoin the same code when it's our turn.</summary>
        private static void OnNewHost(TeamPeer from, TeamMessage message)
        {
            if (IsHost || from == null || !from.IsHost || string.IsNullOrEmpty(message.code))
                return;

            string code = message.code;
            string pwd = password;
            string name = string.IsNullOrEmpty(message.name) ? "your teammate" : message.name;
            var hint = TeamAddress.Parse(message.f);

            Leave(null, true);
            AddSystem(from.Name + " made " + name + " the host. Reconnecting to them...");
            ScheduleRejoin(FirstRejoin + RejoinGap * Math.Max(0, message.n), code, pwd, hint, "Reconnecting to " + name + "...");
            Raise();
        }

        /// <summary>The new host: once its internet address is known, claim the old host's invite instead of making one.</summary>
        private static bool ApplyTakeover()
        {
            if (takeover == null)
                return false;
            secret = takeover.Secret;
            if (!string.IsNullOrEmpty(takeover.PeerKey))
                peerKey = takeover.PeerKey;
            handledGuestAt = takeover.HandledGuestAt;
            takeover = null;
            lastPoll = 0;
            Step("Took over session " + Code);
            Status = WaitingText();
            return true;
        }

        /// <summary>
        /// Unity is reloading scripts in the middle of a handoff. True when that's been dealt with (so the normal
        /// reload handling is skipped).
        /// </summary>
        private static bool SuspendHandoff()
        {
            // The old host, a moment before leaving: leave now. Its rejoin is already saved to disk.
            if (handingOff && IsHost)
            {
                Leave(null, true, true);
                return true;
            }

            // The new host, still finding its address: take the invite over again after the reload (not a new one).
            if (takeover != null && IsHost)
            {
                SessionState.SetString(ResumeKey, UnityEngine.JsonUtility.ToJson(new TeamSaved
                {
                    restart = true,
                    host = true,
                    code = Code,
                    password = password,
                    takeoverSecret = takeover.Secret,
                    takeoverKey = takeover.PeerKey,
                    takeoverHandled = takeover.HandledGuestAt,
                    savedAt = DateTime.UtcNow.Ticks
                }));
                suspending = true;
                Close();
                return true;
            }
            return false;
        }

        /// <summary>After a reload: carry on taking the invite over.</summary>
        private static bool ResumeTakeover(TeamSaved saved)
        {
            if (!saved.host || string.IsNullOrEmpty(saved.takeoverSecret) || string.IsNullOrEmpty(saved.code))
                return false;
            Reset();
            ClearModules();
            IsHost = true;
            password = saved.password ?? string.Empty;
            Code = saved.code;
            takeover = new Takeover { Secret = saved.takeoverSecret, PeerKey = saved.takeoverKey, HandledGuestAt = saved.takeoverHandled };
            Prepare();
            return true;
        }

        /// <summary>A guest rejoining after a handoff also knocks on the address the old host knew the new host by.</summary>
        private static void AddHandoffHint(List<IPEndPoint> candidates)
        {
            var hint = handoffHint;
            handoffHint = null;
            if (hint != null && !candidates.Any(c => c.Equals(hint)))
                candidates.Add(hint);
        }
    }
}
#endif
