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

namespace WPFMA
{
    internal static class WPFMAWorldTypes
    {
        internal const string SceneDescriptor = "VRC.SDK3.Components.VRCSceneDescriptor";
        internal const string SceneDescriptorBase = "VRC.SDKBase.VRC_SceneDescriptor";
        internal const string Mirror = "VRC.SDKBase.VRC_MirrorReflection";
        internal const string Station = "VRC.SDK3.Components.VRCStation";
        internal const string Pickup = "VRC.SDK3.Components.VRCPickup";
        internal const string Pedestal = "VRC.SDK3.Components.VRCAvatarPedestal";
        internal const string UnityVideo = "VRC.SDK3.Video.Components.VRCUnityVideoPlayer";
        internal const string AVProVideo = "VRC.SDK3.Video.Components.AVPro.VRCAVProVideoPlayer";
        internal const string Udon = "VRC.Udon.UdonBehaviour";

        internal const string WorldPackage = "Packages/com.vrchat.worlds";
        internal const string WorldPagePrefKey = "WPFMA.Tools.WorldPage";

        private static readonly Dictionary<string, Type> Cache = new Dictionary<string, Type>();
        private static readonly Dictionary<string, KeyValuePair<double, List<Component>>> ObjectCache =
            new Dictionary<string, KeyValuePair<double, List<Component>>>();
        private static readonly Dictionary<string, string> PrefabCache = new Dictionary<string, string>();
        private static double boundsAt = -10;
        private static Bounds cachedBounds;
        private static bool hooked;

        private static void Hook()
        {
            if (hooked)
                return;
            hooked = true;
            EditorApplication.hierarchyChanged += Invalidate;
            EditorApplication.projectChanged += () => PrefabCache.Clear();
        }

        internal static void Invalidate()
        {
            ObjectCache.Clear();
            boundsAt = -10;
        }

        internal static bool WorldSdkInstalled
        {
            get { return Find(SceneDescriptor) != null; }
        }

        internal static Type Find(string name)
        {
            Type found;
            if (Cache.TryGetValue(name, out found))
                return found;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                try
                {
                    found = assembly.GetType(name, false);
                    if (found != null)
                        break;
                }
                catch (Exception)
                {
                }
            }

            Cache[name] = found;
            return found;
        }

        internal static List<Component> Objects(string typeName)
        {
            Hook();
            var type = Find(typeName);
            if (type == null)
                return new List<Component>();

            double now = EditorApplication.timeSinceStartup;
            KeyValuePair<double, List<Component>> cached;
            if (ObjectCache.TryGetValue(typeName, out cached) && now - cached.Key < 1.0 && now >= cached.Key &&
                cached.Value.All(c => c != null))
                return cached.Value;

            var found = UnityEngine.Object.FindObjectsOfType(type, true)
                .OfType<Component>()
                .Where(c => c != null && !EditorUtility.IsPersistent(c) && c.gameObject.scene.IsValid())
                .ToList();
            ObjectCache[typeName] = new KeyValuePair<double, List<Component>>(now, found);
            return found;
        }

        internal static Component Descriptor()
        {
            return Objects(SceneDescriptorBase).FirstOrDefault();
        }

        internal static string SdkPrefab(string fileName)
        {
            Hook();
            string cachedPath;
            if (PrefabCache.TryGetValue(fileName, out cachedPath))
                return cachedPath;

            PrefabCache[fileName] = null;
            if (!Directory.Exists(WorldPackage))
                return null;

            string name = Path.GetFileNameWithoutExtension(fileName);
            foreach (var guid in AssetDatabase.FindAssets(name + " t:Prefab", new[] { WorldPackage }))
            {
                string path = AssetDatabase.GUIDToAssetPath(guid);
                if (Path.GetFileName(path) == fileName)
                    return PrefabCache[fileName] = path;
            }

            return null;
        }

        internal static Vector3 PlacementPoint()
        {
            var view = SceneView.lastActiveSceneView;
            if (view == null)
                return Vector3.zero;

            var pivot = view.pivot;
            RaycastHit hit;
            if (Physics.Raycast(pivot + Vector3.up * 2f, Vector3.down, out hit, 50f))
                return hit.point;
            return pivot;
        }

        internal static IEnumerable<GameObject> SceneObjects()
        {
            for (int i = 0; i < EditorSceneManager.sceneCount; i++)
            {
                var scene = EditorSceneManager.GetSceneAt(i);
                if (!scene.isLoaded)
                    continue;

                foreach (var root in scene.GetRootGameObjects())
                {
                    foreach (var transform in root.GetComponentsInChildren<Transform>(true))
                        yield return transform.gameObject;
                }
            }
        }

        internal static Bounds SceneBounds()
        {
            Hook();
            double now = EditorApplication.timeSinceStartup;
            if (now - boundsAt < 2.0 && now >= boundsAt)
                return cachedBounds;

            cachedBounds = ComputeBounds();
            boundsAt = now;
            return cachedBounds;
        }

        private static Bounds ComputeBounds()
        {
            bool any = false;
            var bounds = new Bounds();

            foreach (var renderer in UnityEngine.Object.FindObjectsOfType<Renderer>())
            {
                if (renderer is ParticleSystemRenderer || !renderer.enabled || !renderer.gameObject.activeInHierarchy)
                    continue;
                if (renderer.gameObject.CompareTag("EditorOnly"))
                    continue;

                if (!any)
                {
                    bounds = renderer.bounds;
                    any = true;
                }
                else
                {
                    bounds.Encapsulate(renderer.bounds);
                }
            }

            return any ? bounds : new Bounds(Vector3.zero, Vector3.one * 10f);
        }

        internal static string SceneFolder()
        {
            string scene = EditorSceneManager.GetActiveScene().name;
            if (string.IsNullOrEmpty(scene))
                scene = "Untitled";
            return "Assets/World/" + WPFMAPaths.SafeFileName(scene);
        }

        internal static void Reveal(int page, string prefKey)
        {
            EditorPrefs.SetInt(WorldPagePrefKey, page);
            if (!string.IsNullOrEmpty(prefKey))
                EditorPrefs.SetBool(prefKey, true);
            WPFMAWindow.OpenAt(WPFMAWindow.Tab.Tools);
        }

        internal static void NeedsWorldSdk()
        {
            EditorGUILayout.LabelField(new GUIContent("Needs the VRChat world SDK.", "This part needs the VRChat world SDK, which is not in this project. In a world project it works here."), WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
        }
    }

    internal static class WPFMAIssueView
    {
        internal static void Draw(WPFMAPreUploadCheck.Issue issue, Action rerun, Action<int, string> reveal)
        {
            Color color;
            string mark;
            switch (issue.Severity)
            {
                case WPFMAPreUploadCheck.Severity.Error:
                    color = WPFMAToolSection.ErrorRed;
                    mark = "✖";
                    break;
                case WPFMAPreUploadCheck.Severity.Warning:
                    color = WPFMAToolSection.WarnAmber;
                    mark = "▲";
                    break;
                default:
                    color = WPFMAToolSection.AccentBlue;
                    mark = "●";
                    break;
            }

            EditorGUILayout.Space(4f);
            var rect = EditorGUILayout.BeginVertical();
            EditorGUI.DrawRect(new Rect(rect.x, rect.y, 3f, rect.height), color);

            EditorGUILayout.LabelField(mark + "  " + issue.Title,
                new GUIStyle(EditorStyles.boldLabel) { wordWrap = true, normal = { textColor = color } });

            if (!string.IsNullOrEmpty(issue.Detail))
                EditorGUILayout.LabelField(issue.Detail, WPFMAToolSection.Hint(WPFMAToolSection.MetaText));

            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.Space(14f);

                if (issue.Fix != null && GUILayout.Button(issue.FixLabel ?? "Fix", EditorStyles.miniButton, GUILayout.Width(170f)))
                {
                    var fix = issue.Fix;
                    var chosen = issue;
                    EditorApplication.delayCall += () =>
                    {
                        WPFMAChangeLog.Run("World check", "\"" + chosen.FixLabel + "\" - " + chosen.Title, chosen.Assets, chosen.Scene,
                            () => { fix(); return "Fixed: " + chosen.Title; });
                        if (rerun != null)
                            rerun();
                    };
                }

                if (issue.Show != null && issue.Show.Length > 0 && GUILayout.Button("Show", EditorStyles.miniButton, GUILayout.Width(60f)))
                    Selection.objects = issue.Show.Where(o => o != null).ToArray();

                if (issue.ToolPage >= 0 && reveal != null && GUILayout.Button("Open the tool", EditorStyles.miniButton, GUILayout.Width(100f)))
                {
                    int page = issue.ToolPage;
                    string key = issue.ToolKey;
                    EditorApplication.delayCall += () => reveal(page, key);
                }

                GUILayout.FlexibleSpace();
            }

            EditorGUILayout.EndVertical();
        }
    }
}
#endif
