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

namespace WPFMA
{
    internal static class WPFMATextureOptimizer
    {
        internal sealed class Entry
        {
            public Texture2D Texture;
            public TextureImporter Importer;
            public long Bytes;
            public bool Editable;
            /// <summary>A colour ramp or lookup texture (tiny, or long and thin): compressing those makes visible bands.</summary>
            public bool Ramp;
        }

        internal sealed class Settings
        {
            public int MaxSize = 2048;
            public bool Compress = true;
            public bool Crunch;
            public int CrunchQuality = 60;
            public bool StreamingMips = true;
            public bool AndroidOverride = true;
            public int AndroidMaxSize = 1024;
            public bool KeepRamps = true;
            public bool Mipmaps;
        }

        private static MethodInfo storageSize;

        internal static List<Entry> Collect(GameObject root)
        {
            var renderers = root != null
                ? root.GetComponentsInChildren<Renderer>(true)
                : UnityEngine.Object.FindObjectsOfType<Renderer>(true).Where(r => r.gameObject.scene.IsValid()).ToArray();

            var materials = renderers.SelectMany(r => r.sharedMaterials).Concat(AnimatedMaterials(root)).Where(m => m != null).Distinct().ToArray();
            var textures = new HashSet<Texture2D>();

            foreach (var material in materials)
            {
                var shader = material.shader;
                if (shader == null)
                    continue;

                for (int i = 0; i < shader.GetPropertyCount(); i++)
                {
                    if (shader.GetPropertyType(i) != UnityEngine.Rendering.ShaderPropertyType.Texture)
                        continue;

                    var texture = material.GetTexture(shader.GetPropertyNameId(i)) as Texture2D;
                    if (texture != null)
                        textures.Add(texture);
                }
            }

            if (root == null)
            {
                foreach (var data in LightmapSettings.lightmaps)
                {
                    if (data.lightmapColor != null)
                        textures.Remove(data.lightmapColor);
                }
            }

            return textures.Select(t =>
            {
                string path = AssetDatabase.GetAssetPath(t);
                var importer = AssetImporter.GetAtPath(path) as TextureImporter;
                return new Entry
                {
                    Texture = t,
                    Importer = importer,
                    Bytes = Size(t),
                    Editable = importer != null && path.StartsWith("Assets/"),
                    Ramp = IsRamp(t)
                };
            }).OrderByDescending(e => e.Bytes).ToList();
        }

        /// <summary>Materials an avatar's animations swap in (material toggles), which aren't on any renderer until then.</summary>
        private static IEnumerable<Material> AnimatedMaterials(GameObject root)
        {
            var materials = new HashSet<Material>();
            if (root == null)
                return materials;

            var clips = WPFMAAvatarAnimations.Sources(root, true).SelectMany(s => s.Clips).Concat(WPFMAAvatarAnimations.Use(root).Clips).Distinct();
            foreach (var clip in clips)
            {
                foreach (var binding in AnimationUtility.GetObjectReferenceCurveBindings(clip))
                {
                    if (!binding.propertyName.StartsWith("m_Materials", StringComparison.Ordinal))
                        continue;
                    foreach (var key in AnimationUtility.GetObjectReferenceCurve(clip, binding))
                    {
                        var material = key.value as Material;
                        if (material != null)
                            materials.Add(material);
                    }
                }
            }
            return materials;
        }

        internal static bool IsRamp(Texture texture)
        {
            int small = Math.Min(texture.width, texture.height), big = Math.Max(texture.width, texture.height);
            return big <= 128 || (small <= 64 && big >= small * 4);
        }

        private static bool AddsMips(Entry entry, Settings settings)
        {
            var importer = entry.Importer;
            return settings.Mipmaps && importer != null && !importer.mipmapEnabled && !entry.Ramp &&
                   (importer.textureType == TextureImporterType.Default || importer.textureType == TextureImporterType.NormalMap) &&
                   Math.Max(entry.Texture.width, entry.Texture.height) >= 256;
        }

        /// <summary>
        /// About how much video memory the texture will take after Apply: smaller sizes cut it by the square, compressing
        /// an uncompressed texture by about 4, mipmaps add a third. Crunch makes the download smaller, not the memory.
        /// </summary>
        internal static long Estimate(Entry entry, Settings settings)
        {
            if (!entry.Editable || entry.Importer == null || entry.Texture == null)
                return entry.Bytes;

            double bytes = entry.Bytes;
            int big = Math.Max(entry.Texture.width, entry.Texture.height);
            if (big > settings.MaxSize)
            {
                double scale = (double)settings.MaxSize / big;
                bytes *= scale * scale;
            }

            if (settings.Compress && !(settings.KeepRamps && entry.Ramp) && entry.Importer.textureCompression == TextureImporterCompression.Uncompressed)
                bytes /= 4.0;
            if (AddsMips(entry, settings))
                bytes *= 4.0 / 3.0;
            return (long)bytes;
        }

        internal static long Size(Texture texture)
        {
            if (storageSize == null)
            {
                var util = typeof(UnityEditor.Editor).Assembly.GetType("UnityEditor.TextureUtil");
                storageSize = util != null ? util.GetMethod("GetStorageMemorySizeLong", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) : null;
            }

            try
            {
                if (storageSize != null)
                    return (long)storageSize.Invoke(null, new object[] { texture });
            }
            catch (Exception)
            {
            }

            return UnityEngine.Profiling.Profiler.GetRuntimeMemorySizeLong(texture);
        }

        internal static string Apply(List<Entry> entries, Settings settings)
        {
            var editable = entries.Where(e => e.Editable).ToList();
            int changed = 0;

            try
            {
                AssetDatabase.StartAssetEditing();
                for (int i = 0; i < editable.Count; i++)
                {
                    var importer = editable[i].Importer;
                    EditorUtility.DisplayProgressBar("Texture optimizer", importer.assetPath, i / (float)Math.Max(1, editable.Count));

                    bool dirty = false;
                    bool keepSharp = settings.KeepRamps && editable[i].Ramp;

                    if (importer.maxTextureSize > settings.MaxSize)
                    {
                        importer.maxTextureSize = settings.MaxSize;
                        dirty = true;
                    }

                    if (settings.Compress && !keepSharp && importer.textureCompression == TextureImporterCompression.Uncompressed)
                    {
                        importer.textureCompression = TextureImporterCompression.Compressed;
                        dirty = true;
                    }

                    if (settings.Crunch && !keepSharp && importer.textureType != TextureImporterType.NormalMap &&
                        (!importer.crunchedCompression || importer.compressionQuality != settings.CrunchQuality))
                    {
                        importer.crunchedCompression = true;
                        importer.compressionQuality = settings.CrunchQuality;
                        dirty = true;
                    }

                    if (AddsMips(editable[i], settings))
                    {
                        importer.mipmapEnabled = true;
                        dirty = true;
                    }

                    if (importer.mipmapEnabled && settings.StreamingMips && !importer.streamingMipmaps)
                    {
                        importer.streamingMipmaps = true;
                        dirty = true;
                    }

                    if (settings.AndroidOverride)
                    {
                        var android = importer.GetPlatformTextureSettings("Android");
                        if (!android.overridden || android.maxTextureSize > settings.AndroidMaxSize)
                        {
                            android.overridden = true;
                            android.maxTextureSize = Math.Min(settings.AndroidMaxSize, settings.MaxSize);
                            android.format = TextureImporterFormat.ASTC_6x6;
                            importer.SetPlatformTextureSettings(android);
                            dirty = true;
                        }
                    }

                    if (dirty)
                    {
                        importer.SaveAndReimport();
                        changed++;
                    }
                }
            }
            finally
            {
                AssetDatabase.StopAssetEditing();
                EditorUtility.ClearProgressBar();
            }

            int locked = entries.Count - editable.Count;
            return "Updated " + changed + " texture(s)." + (locked > 0 ? " " + locked + " inside packages were left alone." : string.Empty);
        }
    }

    internal static class WPFMATextureOptimizerSection
    {
        private const string PrefKey = "WPFMA.Tools.TextureOptimizerExpanded";
        private static readonly int[] Sizes = { 256, 512, 1024, 2048, 4096 };
        private static readonly string[] SizeNames = { "256", "512", "1024", "2048", "4096" };

        private static readonly WPFMATextureOptimizer.Settings Settings = new WPFMATextureOptimizer.Settings();
        private static List<WPFMATextureOptimizer.Entry> entries;
        private static GameObject scannedRoot;
        private static bool scannedWorld;
        private static string status;
        private static Vector2 scroll;

        internal static void Draw(GUIStyle sectionStyle)
        {
            string detail = entries == null ? "not scanned yet" : entries.Count + " texture(s), " + Mb(entries.Sum(e => e.Bytes));
            WPFMAToolSection.Draw(sectionStyle, "Texture optimizer", detail, PrefKey, Body);
        }

        private static void Body()
        {
            bool world = WPFMA.Editor.WPFMAInstaller.PanelKind == WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds;
            var root = world ? null : WPFMAAvatarFolders.AvatarRoot(Selection.activeGameObject);

            EditorGUILayout.LabelField(new GUIContent("Shrink and compress textures.",
                (world ? "Every texture used in the open scene" : "Every texture the selected avatar uses") +
                ", with the biggest first. Cap their size, compress them and add Quest settings in one go - textures are " +
                "usually most of the download size."),
                WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            if (!world && root == null)
            {
                EditorGUILayout.LabelField("Select the avatar in the Hierarchy.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

            if (GUILayout.Button(entries == null || scannedRoot != root || scannedWorld != world ? "Scan" : "Scan again", GUILayout.Height(22f)))
            {
                EditorApplication.delayCall += () =>
                {
                    entries = WPFMATextureOptimizer.Collect(root);
                    scannedRoot = root;
                    scannedWorld = world;
                    status = null;
                };
            }

            if (entries == null || scannedRoot != root || scannedWorld != world)
                return;

            WPFMAToolDefaults.Load(Settings);
            int sizeIndex = Mathf.Max(0, Array.IndexOf(Sizes, Settings.MaxSize));
            Settings.MaxSize = Sizes[EditorGUILayout.Popup("Max size", sizeIndex, SizeNames)];
            Settings.Compress = EditorGUILayout.ToggleLeft("Compress uncompressed textures", Settings.Compress);
            Settings.Crunch = EditorGUILayout.ToggleLeft(new GUIContent("Crunch compression", "Much smaller download, slightly softer."), Settings.Crunch);
            if (Settings.Crunch)
                Settings.CrunchQuality = EditorGUILayout.IntSlider("  Crunch quality", Settings.CrunchQuality, 0, 100);
            Settings.StreamingMips = EditorGUILayout.ToggleLeft("Streaming mipmaps (less memory in game)", Settings.StreamingMips);
            Settings.AndroidOverride = EditorGUILayout.ToggleLeft("Quest settings (ASTC 6x6)", Settings.AndroidOverride);
            if (Settings.AndroidOverride)
            {
                int androidIndex = Mathf.Max(0, Array.IndexOf(Sizes, Settings.AndroidMaxSize));
                Settings.AndroidMaxSize = Sizes[EditorGUILayout.Popup("  Quest max size", androidIndex, SizeNames)];
            }
            Settings.KeepRamps = EditorGUILayout.ToggleLeft(new GUIContent("Keep colour ramps and lookup textures sharp", "No compression."), Settings.KeepRamps);
            Settings.Mipmaps = EditorGUILayout.ToggleLeft(new GUIContent("Turn on mipmaps where they're off", "No shimmering far away, a third more memory."), Settings.Mipmaps);
            WPFMAToolDefaults.Save(Settings);

            long now = entries.Sum(e => e.Bytes);
            long after = entries.Sum(e => WPFMATextureOptimizer.Estimate(e, Settings));
            int noMips = entries.Count(e => e.Importer != null && !e.Importer.mipmapEnabled && !e.Ramp && e.Texture != null &&
                                            Math.Max(e.Texture.width, e.Texture.height) >= 256);
            EditorGUILayout.Space(2f);
            EditorGUILayout.LabelField("Video memory: " + Mb(now) + " now, about " + Mb(after) + " after.",
                WPFMAToolSection.Hint(after < now ? WPFMAToolSection.OkGreen : WPFMAToolSection.MetaText));
            if (noMips > 0 && !Settings.Mipmaps)
                EditorGUILayout.LabelField(noMips + " texture(s) have mipmaps off, so they shimmer when seen from far away.",
                    WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            EditorGUILayout.Space(4f);
            scroll = EditorGUILayout.BeginScrollView(scroll, GUILayout.MaxHeight(220f));
            foreach (var entry in entries)
            {
                if (entry.Texture == null)
                    continue;

                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.ObjectField(entry.Texture, typeof(Texture2D), false);
                    string info = entry.Texture.width + "x" + entry.Texture.height;
                    if (entry.Importer != null)
                        info += "  max " + entry.Importer.maxTextureSize + (entry.Importer.textureCompression == TextureImporterCompression.Uncompressed ? "  uncompressed" : string.Empty) +
                                (entry.Importer.crunchedCompression ? "  crunched" : string.Empty) +
                                (entry.Ramp ? "  ramp" : string.Empty);
                    EditorGUILayout.LabelField(info, WPFMAToolSection.Hint(entry.Editable ? WPFMAToolSection.FaintText : WPFMAToolSection.WarnAmber), GUILayout.Width(220f));
                    EditorGUILayout.LabelField(Mb(entry.Bytes), WPFMAToolSection.Hint(WPFMAToolSection.MetaText), GUILayout.Width(60f));
                }
            }
            EditorGUILayout.EndScrollView();

            using (new EditorGUI.DisabledScope(!entries.Any(e => e.Editable)))
            {
                if (GUILayout.Button("Apply to " + entries.Count(e => e.Editable) + " texture(s)", GUILayout.Height(26f)))
                {
                    var list = entries;
                    EditorApplication.delayCall += () =>
                    {
                        var metas = WPFMAChangeLog.MetaPaths(list.Where(e => e.Editable && e.Importer != null).Select(e => e.Importer.assetPath)).ToList();
                        status = WPFMAChangeLog.Run("Texture optimizer", "Optimize " + metas.Count + " texture(s)", metas, false,
                            () => WPFMATextureOptimizer.Apply(list, Settings));
                        entries = WPFMATextureOptimizer.Collect(root);
                        Debug.Log("[WPFMA-SDK] Texture optimizer: " + status);
                    };
                }
            }

            EditorGUILayout.LabelField(new GUIContent("Changes import settings.", "This changes the textures' import settings, so every material using them is affected. Lightmaps are left alone."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            if (!string.IsNullOrEmpty(status))
                EditorGUILayout.LabelField(status, WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
        }

        private static string Mb(long bytes)
        {
            return (bytes / (1024.0 * 1024.0)).ToString("0.0") + " MB";
        }
    }
}
#endif
