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

namespace WPFMA.Vrca
{
    public static class WPFMAVrcaPreview
    {
        public const string PreviewRootName = "WPFMA-SDK VRCA Preview";

        private static readonly Dictionary<string, AssetBundle> Loaded =
            new Dictionary<string, AssetBundle>(StringComparer.OrdinalIgnoreCase);

        public static bool HasPreview
        {
            get { return FindPreviewRoot() != null; }
        }

        public static bool IsBuildTargetCompatible(out string reason)
        {
            var target = EditorUserBuildSettings.activeBuildTarget;
            if (target == BuildTarget.StandaloneWindows64 || target == BuildTarget.StandaloneWindows ||
                target == BuildTarget.Android || target == BuildTarget.iOS)
            {
                reason = null;
                return true;
            }

            bool standalone = target == BuildTarget.StandaloneLinux64 || target == BuildTarget.StandaloneOSX;

            reason = "The active build target is " + target + ". " +
                     (standalone
                         ? "PC .vrca files are Windows bundles, and a bundle only loads on the target it was built " +
                           "for - so the editor has to be switched to Windows even when it is running on " +
                           (target == BuildTarget.StandaloneLinux64 ? "Linux" : "macOS") + ".\n\n" +
                           "File > Build Settings > Windows, then Switch Platform. Windows Build Support has to be " +
                           "installed for this editor version in Unity Hub; it is a module, not a separate install."
                         : "PC .vrca bundles need the Windows target and Quest bundles need Android " +
                           "(File > Build Settings).");
            return false;
        }

        public static bool EnsureBuildTarget()
        {
            string reason;
            if (IsBuildTargetCompatible(out reason))
                return true;

            if (EditorUtility.DisplayDialog("WPFMA-SDK", reason, "Open Build Settings", "Cancel"))
                EditorApplication.ExecuteMenuItem("File/Build Settings...");
            return false;
        }

        public static GameObject Preview(string vrcaPath, out string message)
        {
            message = null;

            if (!File.Exists(vrcaPath))
            {
                message = "That file no longer exists.";
                return null;
            }

            AssetBundle bundle;
            if (!Loaded.TryGetValue(vrcaPath, out bundle) || bundle == null)
            {
                bundle = LoadBundle(vrcaPath, out message);
                if (bundle == null)
                    return null;

                Loaded[vrcaPath] = bundle;
            }

            lastPreviewedPath = vrcaPath;

            if (bundle.isStreamedSceneAssetBundle)
            {
                message = "This bundle holds a world, not an avatar, so there is no prefab to spawn. " +
                          "Use Play scene on its row to load it in play mode.";
                return null;
            }

            var prefabs = bundle.LoadAllAssets<GameObject>();
            if (prefabs == null || prefabs.Length == 0)
            {
                message = "The bundle loaded but contains no GameObject to preview.";
                return null;
            }

            var root = FindPreviewRoot();
            if (root == null)
            {
                root = new GameObject(PreviewRootName);
                Undo.RegisterCreatedObjectUndo(root, "Create VRCA preview root");
            }

            GameObject first = null;
            foreach (var prefab in prefabs)
            {
                if (prefab == null || prefab.transform.parent != null)
                    continue;

                var instance = UnityEngine.Object.Instantiate(prefab, root.transform);
                instance.name = prefab.name;
                Undo.RegisterCreatedObjectUndo(instance, "Preview VRCA");

                foreach (var warning in WPFMAVrcaExporter.RebindSceneScripts(instance))
                    Debug.LogWarning("[WPFMA-SDK] " + warning);

                RebindUnsupportedShaders(instance);

                if (first == null)
                    first = instance;
            }

            if (first == null)
            {
                message = "The bundle contains no root GameObject to preview.";
                return null;
            }

            Selection.activeGameObject = first;
            var sceneView = SceneView.lastActiveSceneView;
            if (sceneView != null)
                sceneView.FrameSelected();

            message = "Loaded '" + first.name + "'.";
            return first;
        }

        private const string ForceShaderRebindKey = "WPFMA.Preview.ForceShaderRebind";

        public static bool ForceShaderRebind
        {
            get { return EditorPrefs.GetBool(ForceShaderRebindKey, false); }
            set { EditorPrefs.SetBool(ForceShaderRebindKey, value); }
        }

        public static void RebindUnsupportedShaders(GameObject instance)
        {
            if (instance == null)
                return;

            bool force = ForceShaderRebind;
            var swapped = new Dictionary<Material, Material>();
            var reported = new HashSet<string>();
            List<Shader> candidates = null;
            int count = 0;

            foreach (var renderer in instance.GetComponentsInChildren<Renderer>(true))
            {
                if (renderer == null)
                    continue;

                var materials = renderer.sharedMaterials;
                if (materials == null)
                    continue;

                bool changed = false;
                for (int i = 0; i < materials.Length; i++)
                {
                    var material = materials[i];
                    if (material == null || !NeedsRebind(material, force))
                        continue;

                    Material replacement;
                    if (!swapped.TryGetValue(material, out replacement))
                    {
                        if (candidates == null)
                            candidates = CollectCandidates();

                        replacement = Rebind(material, candidates, reported);
                        swapped[material] = replacement;
                        if (replacement != material)
                            count++;
                    }

                    if (replacement != material)
                    {
                        materials[i] = replacement;
                        changed = true;
                    }
                }

                if (changed)
                    renderer.sharedMaterials = materials;
            }

            if (count > 0)
                Debug.Log("[WPFMA-SDK] Preview: rebound " + count + " material(s) to project shaders. " +
                          "The bundle's own shaders hold no code this editor's graphics API can run, which is " +
                          "what makes them draw magenta.");
        }

        private static bool NeedsRebind(Material material, bool force)
        {
            var shader = material.shader;
            if (shader == null)
                return true;

            if (shader.name.IndexOf("InternalError", StringComparison.OrdinalIgnoreCase) >= 0)
                return true;

            if (force)
                return true;

            if (Application.platform == RuntimePlatform.WindowsEditor)
                return false;

            return !shader.isSupported;
        }

        private static Material Rebind(Material material, List<Shader> candidates, HashSet<string> reported)
        {
            string wanted = material.shader != null ? material.shader.name : null;

            Shader replacement = null;
            if (!string.IsNullOrEmpty(wanted))
            {
                replacement = Shader.Find(wanted);
                if (replacement != null && replacement.name.IndexOf("InternalError", StringComparison.OrdinalIgnoreCase) >= 0)
                    replacement = null;

                if (replacement == null)
                {
                    string reason;
                    replacement = WPFMAShaderResolver.FindFamilyMatch(wanted, candidates, out reason);
                    if (replacement != null && reason != null && reported.Add(reason))
                        Debug.Log("[WPFMA-SDK] Preview: " + reason + ".");
                }
            }

            if (replacement == null)
            {
                if (wanted != null && reported.Add(wanted))
                    Debug.LogWarning("[WPFMA-SDK] Preview: '" + wanted + "' is not installed in this project and " +
                                     "nothing matches it, so the preview uses Standard. Unlock the shader archive " +
                                     "or install it by hand to see this material properly.");

                replacement = Shader.Find("Standard");
                if (replacement == null)
                    return material;
            }

            return new Material(material) { shader = replacement, name = material.name };
        }

        private static List<Shader> CollectCandidates()
        {
            var candidates = new List<Shader>();
            foreach (var info in ShaderUtil.GetAllShaderInfo())
            {
                if (info.hasErrors || info.name.StartsWith("Hidden/", StringComparison.Ordinal))
                    continue;

                var shader = Shader.Find(info.name);
                if (shader != null)
                    candidates.Add(shader);
            }

            return candidates;
        }

        private static AssetBundle LoadBundle(string vrcaPath, out string message)
        {
            message = null;

            var bundle = AssetBundle.LoadFromFile(vrcaPath);
            if (bundle != null)
                return bundle;

            var twin = FindLoadedEquivalent(vrcaPath);
            if (twin != null)
                return twin;

            UnloadStrayBundles();

            bundle = AssetBundle.LoadFromFile(vrcaPath);
            if (bundle != null)
                return bundle;

            string reason;
            if (!IsBuildTargetCompatible(out reason))
            {
                message = reason;
                return null;
            }

            string repackError;
            string repacked = WPFMAVrcaRepack.ToLoadableCopy(vrcaPath, out repackError);
            if (repacked != null)
            {
                bundle = AssetBundle.LoadFromFile(repacked);
                if (bundle != null)
                {
                    Debug.Log("[WPFMA-SDK] Unity would not open " + Path.GetFileName(vrcaPath) +
                              " directly, so it was repacked uncompressed and loaded from that copy.");
                    return bundle;
                }
            }

            message = DescribeLoadFailure(vrcaPath);
            if (repacked == null && !string.IsNullOrEmpty(repackError))
                message += "\n\nRepacking it did not work either: " + repackError;

            return null;
        }

        private static string DescribeLoadFailure(string vrcaPath)
        {
            const string generic = "Unity could not open this bundle. It is either encrypted, built for a " +
                                   "different platform, or built with a Unity version this editor cannot read.";

            try
            {
                using (var stream = File.OpenRead(vrcaPath))
                {
                    var bundle = WPFMAVrcaBundle.Open(stream);
                    if (bundle == null)
                        return generic;

                    if (bundle.IsLegacy)
                    {
                        return "This is a " + bundle.Signature + " archive, built with Unity " + bundle.UnityRevision +
                               ". That is the format VRChat's SDK2 avatars were packed in.' + NL + NL + '" +
                               "This SDK can read it - use Extract files to pull the contents out. Unity itself " +
                               "cannot load an archive this old, so Preview and Export are not available for it " +
                               "in this editor.";
                    }

                    string built = bundle.UnityRevision;
                    int major = MajorVersion(built);
                    int editor = MajorVersion(Application.unityVersion);

                    if (major > editor && editor > 0)
                    {
                        return "This bundle was built with Unity " + built + ", which is newer than this editor (" +
                               Application.unityVersion + "). Unity cannot open a bundle from a later version.";
                    }

                    if (major > 0 && editor > 0 && major < editor)
                    {
                        return "This bundle was built with Unity " + built + ", and this editor is " +
                               Application.unityVersion + ".\n\n" +
                               "Unity cannot open a bundle from an older major version, so it cannot be previewed " +
                               "or exported here. This is the usual answer for old SDK2 avatars.\n\n" +
                               "Extract files still works on it - that path reads the bundle directly instead of " +
                               "asking Unity to load it. For a full rebuild, open it in a project on Unity " +
                               major + ".x instead.";
                    }

                    return "Unity could not open this bundle, though its header reads fine (UnityFS v" +
                           bundle.FormatVersion + ", built with " + built + "). " +
                           "That usually means it is encrypted, or built for a platform this editor is not set to.";
                }
            }
            catch (WPFMAVrcaException e)
            {
                bool legacy = e.Message.IndexOf("legacy", StringComparison.OrdinalIgnoreCase) >= 0;

                return "Unity could not open this bundle, and neither can this SDK.\n\n" + e.Message +
                       (legacy
                           ? "\n\nThat is what old SDK2 avatars are. They were packed in a format Unity " +
                             "retired years ago, so this editor cannot preview or rebuild one at all."
                           : string.Empty);
            }
            catch (Exception)
            {
                return generic;
            }
        }

        private static int MajorVersion(string version)
        {
            if (string.IsNullOrEmpty(version))
                return 0;

            int end = 0;
            while (end < version.Length && char.IsDigit(version[end]))
                end++;

            int value;
            return end > 0 && int.TryParse(version.Substring(0, end), out value) ? value : 0;
        }

        public static AssetBundle GetLoadedBundle(string vrcaPath)
        {
            if (string.IsNullOrEmpty(vrcaPath))
                return null;

            AssetBundle bundle;
            return Loaded.TryGetValue(vrcaPath, out bundle) ? bundle : null;
        }

        public static string GetFirstLoadedPath()
        {
            foreach (var pair in Loaded)
            {
                if (pair.Value != null)
                    return pair.Key;
            }

            return !string.IsNullOrEmpty(lastPreviewedPath) && File.Exists(lastPreviewedPath)
                ? lastPreviewedPath
                : null;
        }

        private const string LastPreviewedPathKey = "WPFMA.VrcaPreview.LastPath";

        private static string lastPreviewedPath
        {
            get { return SessionState.GetString(LastPreviewedPathKey, null); }
            set { SessionState.SetString(LastPreviewedPathKey, value ?? string.Empty); }
        }

        public static GameObject GetPreviewedAvatar()
        {
            var root = FindPreviewRoot();
            if (root == null || root.transform.childCount == 0)
                return null;

            return root.transform.GetChild(root.transform.childCount - 1).gameObject;
        }

        public static void Clear()
        {
            var root = FindPreviewRoot();
            if (root != null)
                Undo.DestroyObjectImmediate(root);

            UnloadAll();
        }

        public static void ForceUnloadAll()
        {
            UnloadAll();
        }

        public static void UnloadStrayBundles()
        {
            var tracked = new HashSet<AssetBundle>(Loaded.Values.Where(b => b != null));
            foreach (var bundle in AssetBundle.GetAllLoadedAssetBundles())
            {
                if (bundle != null && !tracked.Contains(bundle))
                    bundle.Unload(true);
            }
        }

        public static AssetBundle FindLoadedEquivalent(string vrcaPath)
        {
            var wanted = ReadNodeNames(vrcaPath);
            if (wanted == null || wanted.Count == 0)
                return null;

            foreach (var pair in Loaded)
            {
                if (pair.Value == null)
                    continue;

                var loadedNames = ReadNodeNames(pair.Key);
                if (loadedNames != null && loadedNames.SetEquals(wanted))
                    return pair.Value;
            }

            return null;
        }

        private static readonly Dictionary<string, HashSet<string>> NodeNameCache =
            new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);

        private static HashSet<string> ReadNodeNames(string vrcaPath)
        {
            HashSet<string> names;
            if (NodeNameCache.TryGetValue(vrcaPath, out names))
                return names;

            try
            {
                using (var stream = new FileStream(vrcaPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    var container = WPFMAVrcaBundle.Open(stream);
                    names = new HashSet<string>(container.Nodes.Select(n => n.Path));
                }
            }
            catch (Exception)
            {
                names = null;
            }

            NodeNameCache[vrcaPath] = names;
            return names;
        }

        private static void UnloadAll()
        {
            foreach (var pair in Loaded)
            {
                if (pair.Value != null)
                    pair.Value.Unload(true);
            }

            Loaded.Clear();

            foreach (var bundle in AssetBundle.GetAllLoadedAssetBundles())
            {
                if (bundle != null)
                    bundle.Unload(true);
            }
        }

        private static GameObject FindPreviewRoot()
        {
            var scene = EditorSceneManager.GetActiveScene();
            if (!scene.IsValid())
                return null;

            foreach (var go in scene.GetRootGameObjects())
            {
                if (go.name == PreviewRootName)
                    return go;
            }

            return null;
        }

        public static void CreatePreviewScene(bool includeGround)
        {
            if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
                return;

            EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);

            var cameraObject = new GameObject("Main Camera");
            cameraObject.tag = "MainCamera";
            cameraObject.transform.SetPositionAndRotation(new Vector3(0f, 1.1f, 2.4f), Quaternion.Euler(4f, 180f, 0f));
            var camera = cameraObject.AddComponent<Camera>();
            camera.clearFlags = CameraClearFlags.Skybox;
            camera.fieldOfView = 50f;
            camera.nearClipPlane = 0.01f;
            cameraObject.AddComponent<AudioListener>();

            var lightObject = new GameObject("Directional Light");
            lightObject.transform.rotation = Quaternion.Euler(50f, -30f, 0f);
            var light = lightObject.AddComponent<Light>();
            light.type = LightType.Directional;
            light.shadows = LightShadows.Soft;
            light.intensity = 1f;

            if (includeGround)
            {
                var ground = GameObject.CreatePrimitive(PrimitiveType.Cube);
                ground.name = "Ground";
                ground.transform.localScale = new Vector3(4f, 0.1f, 4f);
                ground.transform.position = new Vector3(0f, -0.05f, 0f);
            }
        }
    }
}
#endif
