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

namespace WPFMA.Vrca
{
    [InitializeOnLoad]
    internal static class WPFMAWorldScene
    {
        private const string PendingKey = "WPFMA.WorldScene.Pending";

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

        [Serializable]
        private sealed class RendererLighting
        {
            public string Path;
            public int LightmapIndex;
            public Vector4 ScaleOffset;
        }

        [Serializable]
        private sealed class Capture
        {
            public string Folder;
            public string SceneName;
            public List<string> PrefabPaths = new List<string>();
            public List<string> LightmapColor = new List<string>();
            public List<string> LightmapDirection = new List<string>();
            public List<RendererLighting> Renderers = new List<RendererLighting>();

            public int LightmapsMode;
            public string SkyboxPath;
            public int AmbientMode;
            public Color AmbientSky = Color.gray;
            public Color AmbientEquator = Color.gray;
            public Color AmbientGround = Color.gray;
            public float AmbientIntensity = 1f;
            public bool Fog;
            public int FogMode;
            public Color FogColor = Color.gray;
            public float FogDensity;
            public float FogStart;
            public float FogEnd;
            public float ReflectionIntensity = 1f;
        }

        internal static void CaptureFromPlayMode(string folder, string sceneName, IList<GameObject> roots,
            IList<string> prefabPaths, List<string> warnings)
        {
            if (!EditorApplication.isPlaying)
                return;

            var capture = new Capture
            {
                Folder = folder,
                SceneName = string.IsNullOrEmpty(sceneName) ? "World" : sceneName,
                LightmapsMode = (int)LightmapSettings.lightmapsMode,
                AmbientMode = (int)RenderSettings.ambientMode,
                AmbientSky = RenderSettings.ambientSkyColor,
                AmbientEquator = RenderSettings.ambientEquatorColor,
                AmbientGround = RenderSettings.ambientGroundColor,
                AmbientIntensity = RenderSettings.ambientIntensity,
                Fog = RenderSettings.fog,
                FogMode = (int)RenderSettings.fogMode,
                FogColor = RenderSettings.fogColor,
                FogDensity = RenderSettings.fogDensity,
                FogStart = RenderSettings.fogStartDistance,
                FogEnd = RenderSettings.fogEndDistance,
                ReflectionIntensity = RenderSettings.reflectionIntensity
            };

            foreach (var path in prefabPaths)
            {
                if (!string.IsNullOrEmpty(path))
                    capture.PrefabPaths.Add(path);
            }

            capture.SkyboxPath = SaveSkybox(folder, warnings);
            SaveLightmaps(folder, capture, warnings);
            CaptureRenderers(roots, capture);

            SessionState.SetString(PendingKey, JsonUtility.ToJson(capture));
            Debug.Log("[WPFMA-SDK] Captured the world's lighting: " + capture.LightmapColor.Count +
                      " lightmap(s), " + capture.Renderers.Count + " lit renderer(s). " +
                      "The scene file is written when you leave play mode.");
        }

        private static string SaveSkybox(string folder, List<string> warnings)
        {
            var skybox = RenderSettings.skybox;
            if (skybox == null)
                return null;

            try
            {
                string existing = AssetDatabase.GetAssetPath(skybox);
                if (!string.IsNullOrEmpty(existing))
                    return existing;

                Directory.CreateDirectory(folder + "/Material");
                string path = AssetDatabase.GenerateUniqueAssetPath(folder + "/Material/" + Sanitize(skybox.name) + ".mat");
                AssetDatabase.CreateAsset(UnityEngine.Object.Instantiate(skybox), path);
                return path;
            }
            catch (Exception e)
            {
                warnings.Add("The skybox could not be saved: " + e.Message);
                return null;
            }
        }

        private static void SaveLightmaps(string folder, Capture capture, List<string> warnings)
        {
            var maps = LightmapSettings.lightmaps;
            if (maps == null || maps.Length == 0)
                return;

            Directory.CreateDirectory(folder + "/Lightmaps");

            for (int i = 0; i < maps.Length; i++)
            {
                capture.LightmapColor.Add(SaveLightmap(folder, maps[i].lightmapColor, "lightmap_" + i, false, warnings));
                capture.LightmapDirection.Add(SaveLightmap(folder, maps[i].lightmapDir, "lightmap_" + i + "_dir", true, warnings));
            }
        }

        private static string SaveLightmap(string folder, Texture2D source, string name, bool directional, List<string> warnings)
        {
            if (source == null)
                return null;

            RenderTexture target = null;
            RenderTexture previous = RenderTexture.active;
            try
            {
                target = RenderTexture.GetTemporary(source.width, source.height, 0,
                    RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
                Graphics.Blit(source, target);
                RenderTexture.active = target;

                var readback = new Texture2D(source.width, source.height, TextureFormat.RGBAHalf, false);
                readback.ReadPixels(new Rect(0f, 0f, source.width, source.height), 0, 0);
                readback.Apply();

                string path = folder + "/Lightmaps/" + name + ".exr";
                File.WriteAllBytes(path, readback.EncodeToEXR(Texture2D.EXRFlags.OutputAsFloat));
                UnityEngine.Object.DestroyImmediate(readback);

                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport);
                var importer = AssetImporter.GetAtPath(path) as TextureImporter;
                if (importer != null)
                {
                    importer.textureType = TextureImporterType.Lightmap;
                    importer.sRGBTexture = false;
                    importer.SaveAndReimport();
                }

                return path;
            }
            catch (Exception e)
            {
                warnings.Add("Lightmap '" + name + "' could not be saved: " + e.Message);
                return null;
            }
            finally
            {
                RenderTexture.active = previous;
                if (target != null)
                    RenderTexture.ReleaseTemporary(target);
            }
        }

        private static void CaptureRenderers(IList<GameObject> roots, Capture capture)
        {
            foreach (var root in roots)
            {
                if (root == null)
                    continue;

                foreach (var renderer in root.GetComponentsInChildren<Renderer>(true))
                {
                    if (renderer == null || renderer.lightmapIndex < 0)
                        continue;

                    capture.Renderers.Add(new RendererLighting
                    {
                        Path = PathOf(renderer.transform, root.transform),
                        LightmapIndex = renderer.lightmapIndex,
                        ScaleOffset = renderer.lightmapScaleOffset
                    });
                }
            }
        }

        private static void OnPlayModeChanged(PlayModeStateChange state)
        {
            if (state != PlayModeStateChange.EnteredEditMode)
                return;

            string json = SessionState.GetString(PendingKey, string.Empty);
            if (string.IsNullOrEmpty(json))
                return;

            SessionState.EraseString(PendingKey);

            EditorApplication.delayCall += () => Build(JsonUtility.FromJson<Capture>(json));
        }

        private static void Build(Capture capture)
        {
            if (capture == null || capture.PrefabPaths.Count == 0)
                return;

            var active = SceneManager.GetActiveScene();
            var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive);

            try
            {
                SceneManager.SetActiveScene(scene);

                foreach (var prefabPath in capture.PrefabPaths)
                {
                    var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
                    if (prefab == null)
                        continue;

                    var instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab, scene);
                    if (instance != null)
                        ApplyRendererLighting(instance, capture);
                }

                ApplySettings(capture);

                Directory.CreateDirectory(capture.Folder);
                string path = AssetDatabase.GenerateUniqueAssetPath(
                    capture.Folder + "/" + Sanitize(capture.SceneName) + ".unity");
                EditorSceneManager.SaveScene(scene, path);

                Debug.Log("[WPFMA-SDK] World scene written: " + path +
                          "\n  Open it to see the world with its skybox, ambient, fog and baked lightmaps.");
            }
            catch (Exception e)
            {
                Debug.LogError("[WPFMA-SDK] Could not write the world scene: " + e.Message);
            }
            finally
            {
                if (active.IsValid())
                    SceneManager.SetActiveScene(active);

                EditorSceneManager.CloseScene(scene, true);
            }
        }

        private static void ApplyRendererLighting(GameObject instance, Capture capture)
        {
            if (capture.Renderers.Count == 0)
                return;

            var byPath = new Dictionary<string, RendererLighting>(StringComparer.Ordinal);
            foreach (var entry in capture.Renderers)
            {
                if (entry != null && entry.Path != null)
                    byPath[entry.Path] = entry;
            }

            foreach (var renderer in instance.GetComponentsInChildren<Renderer>(true))
            {
                RendererLighting entry;
                if (renderer == null || !byPath.TryGetValue(PathOf(renderer.transform, instance.transform), out entry))
                    continue;

                renderer.lightmapIndex = entry.LightmapIndex;
                renderer.lightmapScaleOffset = entry.ScaleOffset;
            }
        }

        private static void ApplySettings(Capture capture)
        {
            var maps = new List<LightmapData>();
            for (int i = 0; i < capture.LightmapColor.Count; i++)
            {
                var data = new LightmapData
                {
                    lightmapColor = Load(capture.LightmapColor[i]),
                    lightmapDir = i < capture.LightmapDirection.Count ? Load(capture.LightmapDirection[i]) : null
                };

                maps.Add(data);
            }

            if (maps.Count > 0)
            {
                LightmapSettings.lightmaps = maps.ToArray();
                LightmapSettings.lightmapsMode = (LightmapsMode)capture.LightmapsMode;
            }

            if (!string.IsNullOrEmpty(capture.SkyboxPath))
                RenderSettings.skybox = AssetDatabase.LoadAssetAtPath<Material>(capture.SkyboxPath);

            RenderSettings.ambientMode = (UnityEngine.Rendering.AmbientMode)capture.AmbientMode;
            RenderSettings.ambientSkyColor = capture.AmbientSky;
            RenderSettings.ambientEquatorColor = capture.AmbientEquator;
            RenderSettings.ambientGroundColor = capture.AmbientGround;
            RenderSettings.ambientIntensity = capture.AmbientIntensity;
            RenderSettings.fog = capture.Fog;
            RenderSettings.fogMode = (FogMode)capture.FogMode;
            RenderSettings.fogColor = capture.FogColor;
            RenderSettings.fogDensity = capture.FogDensity;
            RenderSettings.fogStartDistance = capture.FogStart;
            RenderSettings.fogEndDistance = capture.FogEnd;
            RenderSettings.reflectionIntensity = capture.ReflectionIntensity;
        }

        private static Texture2D Load(string path)
        {
            return string.IsNullOrEmpty(path) ? null : AssetDatabase.LoadAssetAtPath<Texture2D>(path);
        }

        private static string PathOf(Transform transform, Transform root)
        {
            if (transform == root)
                return string.Empty;

            var parts = new List<string>();
            for (var current = transform; current != null && current != root; current = current.parent)
                parts.Add(current.name);

            parts.Reverse();
            return string.Join("/", parts.ToArray());
        }

        private static string Sanitize(string name)
        {
            return WPFMAPaths.SafeFileName(name);
        }
    }
}
#endif
