// 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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace WPFMA.Team
{
    /// <summary>A file a guest has that the host doesn't.</summary>
    internal sealed class TeamTheirFile
    {
        public string Path;
        public long Size;
        public bool Code;
    }

    /// <summary>
    /// The host's project is what everyone starts from, so files a guest had before joining stay on their side. This
    /// lets the host see those files and get the ones it wants. The guest's side decides what can be sent with the
    /// usual rules (its paid and private folders never are), scripts still wait for "Trust code" here, and once a
    /// file is here it goes to the other guests like any other change.
    /// </summary>
    internal static partial class TeamFiles
    {
        /// <summary>Host: per guest, the files they have that this project doesn't (as of their last list).</summary>
        internal static readonly Dictionary<string, List<TeamTheirFile>> TheirFiles = new Dictionary<string, List<TeamTheirFile>>();

        private static readonly Dictionary<string, double> theirFilesAsked = new Dictionary<string, double>();

        /// <summary>Host: ask a guest for their file list (at most every few seconds per guest).</summary>
        internal static void AskTheirFiles(TeamPeer peer, bool now = false)
        {
            if (!TeamSession.IsHost || peer == null || peer.Link == null || !peer.Up || Phase != TeamSyncPhase.Live)
                return;
            double at;
            if (theirFilesAsked.TryGetValue(peer.Id, out at) && TeamSession.Now - at < (now ? 3.0 : 120.0))
                return;
            theirFilesAsked[peer.Id] = TeamSession.Now;
            SendTo(For(peer), new TeamMessage { t = "glist" });
        }

        /// <summary>Their files this project still doesn't have (ones that arrived since the list drop off).</summary>
        internal static List<TeamTheirFile> MissingFrom(TeamPeer peer)
        {
            List<TeamTheirFile> list;
            if (peer == null || !TheirFiles.TryGetValue(peer.Id, out list))
                return new List<TeamTheirFile>();
            return list.Where(f => !File.Exists(f.Path) && !IsAwaitingPath(f.Path) && !Pending.Any(p => p.Path == f.Path)).ToList();
        }

        /// <summary>Host: ask the guest to send these.</summary>
        internal static void GetTheirFiles(TeamPeer peer, IEnumerable<string> paths)
        {
            var pf = For(peer);
            if (pf == null)
                return;
            var list = paths.Distinct().ToList();
            for (int i = 0; i < list.Count; i += 400)
                SendTo(pf, new TeamMessage { t = "get", a = list.Skip(i).Take(400).ToArray() });
            AddRecent("Asked " + peer.Name + " for " + list.Count + " of their file(s)");
            TeamSession.AddSystem("Getting " + list.Count + " file(s) from " + peer.Name + ". Your other teammates get them too once they're here.");
        }

        /// <summary>The file-list messages. True if the message was one of them.</summary>
        private static bool OnTheirFilesMessage(PeerFiles pf, TeamMessage message, byte[] blob)
        {
            switch (message.t)
            {
                case "glist":
                    // Guest: send the host what we have. Shared() leaves out our paid and private folders.
                    if (TeamSession.IsHost || pf == null)
                        return true;
                    StartScan(list => SendTo(pf, new TeamMessage { t = "glistr" },
                        Encoding.UTF8.GetBytes(WriteManifest(list.Where(e => !e.Dir && Shared(e.Path)).ToList()))));
                    return true;

                case "glistr":
                    if (!TeamSession.IsHost || pf == null || pf.Peer == null)
                        return true;
                    var theirs = ReadManifest(blob != null ? Encoding.UTF8.GetString(blob) : string.Empty);
                    TheirFiles[pf.Peer.Id] = theirs
                        .Where(e => !e.Dir && Shared(e.Path) && !File.Exists(e.Path))
                        .Select(e => new TeamTheirFile { Path = e.Path, Size = e.Size, Code = IsCode(e.Path) })
                        .OrderBy(f => f.Path, System.StringComparer.OrdinalIgnoreCase)
                        .ToList();
                    TeamSession.Raise();
                    return true;
            }
            return false;
        }

        private static void ForgetTheirFiles(string peerId)
        {
            if (peerId == null)
            {
                TheirFiles.Clear();
                theirFilesAsked.Clear();
                return;
            }
            TheirFiles.Remove(peerId);
            theirFilesAsked.Remove(peerId);
        }
    }
}
#endif
