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

namespace WPFMA.Team
{
    /// <summary>Host: a guest's files this project doesn't have, grouped by folder, to pick and get.</summary>
    internal sealed class TeamTheirFilesWindow : EditorWindow
    {
        private string peerId;
        private readonly HashSet<string> picked = new HashSet<string>();
        private readonly HashSet<string> open = new HashSet<string>();
        private Vector2 scroll;

        internal static void Open(TeamPeer peer)
        {
            var window = GetWindow<TeamTheirFilesWindow>(true, peer.Name + "'s files", true);
            window.minSize = new Vector2(480f, 380f);
            window.peerId = peer.Id;
            window.picked.Clear();
            TeamFiles.AskTheirFiles(peer, true);
        }

        private void OnEnable()
        {
            TeamSession.Changed += Repaint;
        }

        private void OnDisable()
        {
            TeamSession.Changed -= Repaint;
        }

        private static string Size(long bytes)
        {
            return bytes < 1024 * 1024 ? (bytes / 1024 + 1) + " KB" : (bytes / (1024.0 * 1024.0)).ToString("0.0") + " MB";
        }

        // "Assets/Models/Chairs/a.fbx" -> "Assets/Models"
        private static string Folder(string path)
        {
            var parts = path.Split('/');
            return parts.Length > 2 ? parts[0] + "/" + parts[1] : parts[0];
        }

        private void OnGUI()
        {
            var peer = TeamSession.FindPeer(peerId);
            if (peer == null || TeamSession.State != TeamState.Connected)
            {
                EditorGUILayout.HelpBox("That teammate isn't connected any more.", MessageType.Info);
                return;
            }

            var files = TeamFiles.MissingFrom(peer);
            picked.RemoveWhere(p => !files.Any(f => f.Path == p));

            EditorGUILayout.Space(6f);
            EditorGUILayout.LabelField(peer.Name + " has " + files.Count + " file(s) you don't", new GUIStyle(EditorStyles.boldLabel) { fontSize = 13 });
            EditorGUILayout.LabelField("Their paid and private folders are never sent. Scripts and DLLs still wait for Trust code. " +
                                       "Files you get here go to your other teammates too.", EditorStyles.wordWrappedMiniLabel);
            EditorGUILayout.Space(4f);

            using (new EditorGUILayout.HorizontalScope())
            {
                if (GUILayout.Button("Pick all", EditorStyles.miniButtonLeft, GUILayout.Width(70f)))
                    foreach (var f in files)
                        picked.Add(f.Path);
                if (GUILayout.Button("Pick none", EditorStyles.miniButtonRight, GUILayout.Width(70f)))
                    picked.Clear();
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Refresh", EditorStyles.miniButton, GUILayout.Width(70f)))
                    TeamFiles.AskTheirFiles(peer, true);
            }

            scroll = EditorGUILayout.BeginScrollView(scroll);
            foreach (var group in files.GroupBy(f => Folder(f.Path)).OrderBy(g => g.Key))
            {
                var inGroup = group.ToList();
                bool all = inGroup.All(f => picked.Contains(f.Path));
                bool any = inGroup.Any(f => picked.Contains(f.Path));
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUI.showMixedValue = any && !all;
                    bool now = EditorGUILayout.Toggle(all, GUILayout.Width(16f));
                    EditorGUI.showMixedValue = false;
                    if (now != all)
                        foreach (var f in inGroup)
                        {
                            if (now)
                                picked.Add(f.Path);
                            else
                                picked.Remove(f.Path);
                        }
                    bool expanded = open.Contains(group.Key);
                    bool nowOpen = EditorGUILayout.Foldout(expanded, group.Key + "   (" + inGroup.Count + ", " + Size(inGroup.Sum(f => f.Size)) + ")", true);
                    if (nowOpen != expanded)
                    {
                        if (nowOpen)
                            open.Add(group.Key);
                        else
                            open.Remove(group.Key);
                    }
                }
                if (!open.Contains(group.Key))
                    continue;
                foreach (var f in inGroup)
                {
                    using (new EditorGUILayout.HorizontalScope())
                    {
                        GUILayout.Space(22f);
                        bool on = picked.Contains(f.Path);
                        bool now = EditorGUILayout.ToggleLeft(f.Path.Substring(group.Key.Length).TrimStart('/') + (f.Code ? "   (script)" : string.Empty), on);
                        if (now != on)
                        {
                            if (now)
                                picked.Add(f.Path);
                            else
                                picked.Remove(f.Path);
                        }
                        GUILayout.Label(Size(f.Size), EditorStyles.miniLabel, GUILayout.Width(60f));
                    }
                }
            }
            EditorGUILayout.EndScrollView();

            EditorGUILayout.Space(4f);
            var chosen = files.Where(f => picked.Contains(f.Path)).ToList();
            using (new EditorGUI.DisabledScope(chosen.Count == 0))
            {
                if (GUILayout.Button(chosen.Count == 0 ? "Pick files to get" : "Get " + chosen.Count + " file(s), " + Size(chosen.Sum(f => f.Size)), GUILayout.Height(28f)))
                {
                    TeamFiles.GetTheirFiles(peer, chosen.Select(f => f.Path));
                    picked.Clear();
                }
            }
            if (chosen.Any(f => f.Code) && !TeamFiles.TrustCode)
                EditorGUILayout.LabelField("Scripts you pick wait in the Team tab until you allow them.", EditorStyles.wordWrappedMiniLabel);
            EditorGUILayout.Space(6f);
        }
    }
}
#endif
