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

namespace WPFMA.Team
{
    /// <summary>
    /// New assets (and anything they use) can't be dropped into the Scene, Hierarchy or Inspector until the
    /// teammate has received them, so nobody ever sees a missing model, texture or prefab. Assets still on their way
    /// get a small marker in the Project window.
    /// </summary>
    [InitializeOnLoad]
    internal static class TeamGate
    {
        private static double lastWarned = -10;

        static TeamGate()
        {
            DragAndDrop.AddDropHandler(OnSceneDrop);
            DragAndDrop.AddDropHandler(OnHierarchyDrop);
            DragAndDrop.AddDropHandler(OnInspectorDrop);
            EditorApplication.projectWindowItemOnGUI += OnProjectItem;
        }

        /// <summary>The first dragged asset the teammate does not have yet, or null when all of them are there.</summary>
        private static string cachedKey;
        private static string cachedResult;

        internal static string Blocking()
        {
            if (!TeamSession.IsLinked || TeamFiles.AwaitingCount == 0)
                return null;

            // Drag events arrive many times a second; looking up a big prefab's dependencies once per drag is enough.
            var dragged = DragAndDrop.objectReferences;
            string key = TeamFiles.AwaitingCount + ":" + string.Join(",", dragged.Where(o => o != null).Select(o => o.GetInstanceID().ToString()).ToArray());
            if (key == cachedKey)
                return cachedResult;

            cachedKey = key;
            cachedResult = null;
            foreach (var obj in dragged)
            {
                if (obj == null || !EditorUtility.IsPersistent(obj))
                    continue;
                string waiting = TeamFiles.AwaitingDependency(AssetDatabase.GetAssetPath(obj));
                if (waiting != null)
                {
                    cachedResult = waiting;
                    break;
                }
            }
            return cachedResult;
        }

        private static DragAndDropVisualMode Gate(bool perform)
        {
            string waiting = Blocking();
            if (waiting == null)
                return DragAndDropVisualMode.None;

            if (perform || EditorApplication.timeSinceStartup - lastWarned > 2.0)
            {
                lastWarned = EditorApplication.timeSinceStartup;
                string message = (TeamSession.RemoteName ?? "Your teammate") + " is still receiving " + Path.GetFileName(waiting) +
                                 ". You can place it once they have it.";
                var view = SceneView.lastActiveSceneView;
                if (view != null)
                    view.ShowNotification(new GUIContent(message), 2.5);
                if (perform)
                    TeamSession.AddSystem(message);
            }
            return DragAndDropVisualMode.Rejected;
        }

        private static DragAndDropVisualMode OnSceneDrop(Object dropUpon, Vector3 worldPosition, Vector2 viewportPosition, Transform parentForDraggedObjects, bool perform)
        {
            return Gate(perform);
        }

        private static DragAndDropVisualMode OnHierarchyDrop(int dropTargetInstanceID, HierarchyDropFlags dropMode, Transform parentForDraggedObjects, bool perform)
        {
            return Gate(perform);
        }

        private static DragAndDropVisualMode OnInspectorDrop(Object[] targets, bool perform)
        {
            // Dropping onto an asset's own Inspector (e.g. a texture onto a material) is fine: the asset change
            // waits for the teammate on its own. Only scene objects are gated.
            if (targets == null || targets.All(t => t == null || EditorUtility.IsPersistent(t)))
                return DragAndDropVisualMode.None;
            return Gate(perform);
        }

        private static void OnProjectItem(string guid, Rect rect)
        {
            if (!TeamSession.IsLinked)
                return;

            // Outline the asset a teammate has selected, in their color.
            var who = TeamSession.WhoHasAsset(AssetDatabase.GUIDToAssetPath(guid));
            if (who != null)
            {
                var color = who.Color;
                EditorGUI.DrawRect(new Rect(rect.x, rect.yMax - 2f, rect.width, 2f), color);
                EditorGUI.DrawRect(new Rect(rect.x, rect.y, 2f, rect.height), color);
                GUI.Label(rect, new GUIContent(string.Empty, (who.Name ?? "Your teammate") + " has this selected"));
            }

            if (TeamFiles.AwaitingCount == 0 || !TeamFiles.IsAwaitingGuid(guid))
                return;

            var badge = new Rect(rect.xMax - 16f, rect.y, 16f, Mathf.Min(16f, rect.height));
            var style = new GUIStyle(EditorStyles.miniBoldLabel) { normal = { textColor = TeamSession.RemoteColor }, alignment = TextAnchor.MiddleCenter };
            GUI.Label(badge, new GUIContent("⇡", "Still being sent to " + (TeamSession.RemoteName ?? "your teammate") +
                                                 ". It can be placed in the scene once they have it."), style);
        }
    }
}
#endif
