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

namespace WPFMA.Vrca
{
    [InitializeOnLoad]
    internal static class WPFMAScenePreview
    {
        private const string PendingBundleKey = "WPFMA.ScenePreview.Bundle";
        private const string PendingSceneKey = "WPFMA.ScenePreview.Scene";

        private const string ScenePrefix = "BuildPlayer-";

        static WPFMAScenePreview()
        {
            EditorApplication.playModeStateChanged += OnPlayModeChanged;
        }

        internal static bool IsSceneBundle(IEnumerable<WPFMAVrcaNode> nodes)
        {
            if (nodes == null)
                return false;

            foreach (var node in nodes)
            {
                if (node.Path != null && node.Path.StartsWith(ScenePrefix, StringComparison.OrdinalIgnoreCase))
                    return true;
            }

            return false;
        }

        internal static List<string> SceneNames(IEnumerable<WPFMAVrcaNode> nodes)
        {
            var names = new List<string>();
            if (nodes == null)
                return names;

            foreach (var node in nodes)
            {
                if (node.Path == null || !node.Path.StartsWith(ScenePrefix, StringComparison.OrdinalIgnoreCase))
                    continue;

                string name = node.Path.Substring(ScenePrefix.Length);
                if (name.IndexOf('.') >= 0)
                    continue;

                if (!names.Contains(name))
                    names.Add(name);
            }

            return names;
        }

        internal static void Request(string vrcaPath, string sceneName)
        {
            if (string.IsNullOrEmpty(vrcaPath) || !File.Exists(vrcaPath))
                return;

            SessionState.SetString(PendingBundleKey, vrcaPath);
            SessionState.SetString(PendingSceneKey, sceneName ?? string.Empty);

            if (EditorApplication.isPlaying)
                LoadPending();
            else
                EditorApplication.EnterPlaymode();
        }

        private static void OnPlayModeChanged(PlayModeStateChange state)
        {
            if (state == PlayModeStateChange.EnteredPlayMode)
                LoadPending();
        }

        private static AssetBundle FindOrLoad(string vrcaPath)
        {
            var known = WPFMAVrcaPreview.GetLoadedBundle(vrcaPath) ?? WPFMAVrcaPreview.FindLoadedEquivalent(vrcaPath);
            if (known != null)
                return known;

            var expected = ExpectedSceneNames(vrcaPath);
            foreach (var candidate in AssetBundle.GetAllLoadedAssetBundles())
            {
                if (candidate == null || !candidate.isStreamedSceneAssetBundle)
                    continue;

                foreach (var scenePath in candidate.GetAllScenePaths())
                {
                    if (expected.Count > 0 && !expected.Contains(Path.GetFileNameWithoutExtension(scenePath)))
                        continue;

                    return candidate;
                }
            }

            return AssetBundle.LoadFromFile(vrcaPath);
        }

        private static List<string> ExpectedSceneNames(string vrcaPath)
        {
            try
            {
                using (var stream = File.OpenRead(vrcaPath))
                    return SceneNames(WPFMAVrcaBundle.Open(stream).Nodes);
            }
            catch (Exception)
            {
                return new List<string>();
            }
        }

        private static void LoadPending()
        {
            string vrcaPath = SessionState.GetString(PendingBundleKey, string.Empty);
            if (string.IsNullOrEmpty(vrcaPath))
                return;

            string wanted = SessionState.GetString(PendingSceneKey, string.Empty);
            SessionState.EraseString(PendingBundleKey);
            SessionState.EraseString(PendingSceneKey);

            try
            {
                var bundle = FindOrLoad(vrcaPath);
                if (bundle == null)
                {
                    Debug.LogWarning("[WPFMA-SDK] Could not open '" + Path.GetFileName(vrcaPath) +
                                     "' for a scene preview.");
                    return;
                }

                var scenePaths = bundle.GetAllScenePaths();
                if (scenePaths == null || scenePaths.Length == 0)
                {
                    Debug.LogWarning("[WPFMA-SDK] '" + Path.GetFileName(vrcaPath) + "' holds no scene to load.");
                    return;
                }

                string scenePath = scenePaths[0];
                if (!string.IsNullOrEmpty(wanted))
                {
                    foreach (var candidate in scenePaths)
                    {
                        if (Path.GetFileNameWithoutExtension(candidate) != wanted)
                            continue;

                        scenePath = candidate;
                        break;
                    }
                }

                Debug.Log("[WPFMA-SDK] Loading world scene '" + Path.GetFileNameWithoutExtension(scenePath) +
                          "' from " + Path.GetFileName(vrcaPath) +
                          ". Leave play mode to close it; nothing is written to the project.");

                SceneManager.sceneLoaded += OnPreviewSceneLoaded;
                SceneManager.LoadScene(scenePath, LoadSceneMode.Additive);
            }
            catch (Exception e)
            {
                SceneManager.sceneLoaded -= OnPreviewSceneLoaded;
                Debug.LogError("[WPFMA-SDK] Scene preview failed: " + e.Message);
            }
        }

        private static void OnPreviewSceneLoaded(Scene scene, LoadSceneMode mode)
        {
            SceneManager.sceneLoaded -= OnPreviewSceneLoaded;

            try
            {
                foreach (var root in scene.GetRootGameObjects())
                    WPFMAVrcaPreview.RebindUnsupportedShaders(root);
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Could not rebind world shaders: " + e.Message);
            }
        }
    }
}
#endif
