// 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 UnityEngine;

namespace WPFMA
{
    internal static class WPFMAMaterialMerger
    {
        internal sealed class Group
        {
            public Shader Shader;
            public readonly List<MeshRenderer> Renderers = new List<MeshRenderer>();
            public readonly List<Material> Materials = new List<Material>();
            public bool Merge = true;
        }

        internal sealed class Scan
        {
            public readonly List<Group> Groups = new List<Group>();
            public int Skipped;
            public readonly List<string> SkipReasons = new List<string>();
        }

        internal static Scan Find(IEnumerable<MeshRenderer> renderers)
        {
            var scan = new Scan();
            var groups = new Dictionary<Shader, Group>();
            var reasons = new Dictionary<string, int>();

            foreach (var renderer in renderers)
            {
                string reason = Reject(renderer);
                if (reason != null)
                {
                    scan.Skipped++;
                    int count;
                    reasons.TryGetValue(reason, out count);
                    reasons[reason] = count + 1;
                    continue;
                }

                var material = renderer.sharedMaterial;
                Group group;
                if (!groups.TryGetValue(material.shader, out group))
                {
                    group = new Group { Shader = material.shader };
                    groups.Add(material.shader, group);
                }

                group.Renderers.Add(renderer);
                if (!group.Materials.Contains(material))
                    group.Materials.Add(material);
            }

            scan.Groups.AddRange(groups.Values.Where(g => g.Materials.Count > 1).OrderByDescending(g => g.Materials.Count));
            scan.SkipReasons.AddRange(reasons.OrderByDescending(r => r.Value).Select(r => r.Value + " " + r.Key));
            return scan;
        }

        private static string Reject(MeshRenderer renderer)
        {
            if (renderer == null || !renderer.gameObject.scene.IsValid() || renderer.gameObject.CompareTag("EditorOnly"))
                return "not in the scene";

            var filter = renderer.GetComponent<MeshFilter>();
            var mesh = filter != null ? filter.sharedMesh : null;
            if (mesh == null)
                return "with no mesh";

            if (renderer.sharedMaterials.Length != 1 || mesh.subMeshCount != 1)
                return "with several materials on one mesh";

            var material = renderer.sharedMaterial;
            if (material == null || material.shader == null || !material.HasProperty("_MainTex"))
                return "with no main texture slot";

            if (material.mainTextureScale != Vector2.one || material.mainTextureOffset != Vector2.zero)
                return "with tiled or offset textures";

            var uvs = mesh.uv;
            if (uvs == null || uvs.Length == 0)
                return "with no UVs";

            foreach (var uv in uvs)
            {
                if (uv.x < -0.01f || uv.x > 1.01f || uv.y < -0.01f || uv.y > 1.01f)
                    return "whose UVs repeat the texture";
            }

            return null;
        }

        private static bool Emissive(Material material)
        {
            if (material == null || !material.HasProperty("_EmissionColor") || !material.HasProperty("_EmissionMap"))
                return false;
            // The Standard shaders only glow with the keyword on; other shaders decide for themselves.
            // (The saved keyword list, which is what the Inspector's Emission tick sets; IsKeywordEnabled isn't steady here.)
            if (material.shader.name.StartsWith("Standard", StringComparison.Ordinal) && !material.shaderKeywords.Contains("_EMISSION"))
                return false;
            return material.GetColor("_EmissionColor").maxColorComponent > 0.001f;
        }

        /// <summary>
        /// Builds a glow atlas with the same layout as the main one: each material's emission map tinted by its
        /// emission colour, black where a material doesn't glow. Brightness above 1 goes into the merged colour.
        /// </summary>
        private static string PackEmission(List<Material> materials, Rect[] rects, int width, int height, int maxSize, string folder, Material merged)
        {
            float brightest = Mathf.Max(1f, materials.Where(Emissive).Max(m => m.GetColor("_EmissionColor").maxColorComponent));
            var pixels = new Color[width * height];
            for (int i = 0; i < pixels.Length; i++)
                pixels[i] = Color.black;

            for (int index = 0; index < materials.Count; index++)
            {
                var material = materials[index];
                if (!Emissive(material))
                    continue;
                var rect = rects[index];
                int x0 = Mathf.RoundToInt(rect.x * width);
                int y0 = Mathf.RoundToInt(rect.y * height);
                int w = Mathf.Max(1, Mathf.RoundToInt(rect.width * width));
                int h = Mathf.Max(1, Mathf.RoundToInt(rect.height * height));
                var color = material.GetColor("_EmissionColor") / brightest;
                var map = material.GetTexture("_EmissionMap");
                var tile = map != null ? WPFMAThumbnailRenderer.Readable(map, w, h) : Enumerable.Repeat(Color.white, w * h).ToArray();
                for (int y = 0; y < h && y0 + y < height; y++)
                    for (int x = 0; x < w && x0 + x < width; x++)
                    {
                        var c = tile[y * w + x] * color;
                        c.a = 1f;
                        pixels[(y0 + y) * width + x0 + x] = c;
                    }
            }

            var atlas = new Texture2D(width, height, TextureFormat.RGBA32, false);
            try
            {
                atlas.SetPixels(pixels);
                atlas.Apply();
                string path = AssetDatabase.GenerateUniqueAssetPath(folder + "/Atlas Glow.png");
                File.WriteAllBytes(path, atlas.EncodeToPNG());
                AssetDatabase.ImportAsset(path);
                var importer = (TextureImporter)AssetImporter.GetAtPath(path);
                importer.maxTextureSize = maxSize;
                importer.SaveAndReimport();

                merged.SetTexture("_EmissionMap", AssetDatabase.LoadAssetAtPath<Texture2D>(path));
                merged.SetColor("_EmissionColor", new Color(brightest, brightest, brightest, 1f));
                merged.EnableKeyword("_EMISSION");
                merged.globalIlluminationFlags = MaterialGlobalIlluminationFlags.BakedEmissive;
                return path;
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Material merger couldn't pack the glow textures: " + e.Message);
                return null;
            }
            finally
            {
                UnityEngine.Object.DestroyImmediate(atlas);
            }
        }

        internal static string Merge(Group group, int maxSize)
        {
            string folder = WPFMAWorldTypes.SceneFolder() + "/Merged - " + WPFMAPaths.SafeFileName(WPFMAShaderSwap.ShortName(group.Shader.name));
            WPFMAAvatarFolders.Ensure(folder);

            var tiles = new List<Texture2D>();
            try
            {
                EditorUtility.DisplayProgressBar("Material merger", "Reading textures", 0.1f);

                foreach (var material in group.Materials)
                {
                    var source = material.mainTexture;
                    var tint = material.HasProperty("_Color") ? material.GetColor("_Color") : Color.white;
                    int w = source != null ? Mathf.Min(source.width, 1024) : 16;
                    int h = source != null ? Mathf.Min(source.height, 1024) : 16;

                    var pixels = source != null ? WPFMAThumbnailRenderer.Readable(source, w, h) : Enumerable.Repeat(Color.white, w * h).ToArray();
                    for (int i = 0; i < pixels.Length; i++)
                        pixels[i] *= tint;

                    var tile = new Texture2D(w, h, TextureFormat.RGBA32, false);
                    tile.SetPixels(pixels);
                    tile.Apply();
                    tiles.Add(tile);
                }

                EditorUtility.DisplayProgressBar("Material merger", "Packing the atlas", 0.4f);
                var atlas = new Texture2D(2, 2, TextureFormat.RGBA32, false);
                var rects = atlas.PackTextures(tiles.ToArray(), 4, maxSize, false);
                int atlasWidth = atlas.width;
                int atlasHeight = atlas.height;

                string atlasPath = AssetDatabase.GenerateUniqueAssetPath(folder + "/Atlas.png");
                File.WriteAllBytes(atlasPath, atlas.EncodeToPNG());
                UnityEngine.Object.DestroyImmediate(atlas);
                AssetDatabase.ImportAsset(atlasPath);
                var importer = (TextureImporter)AssetImporter.GetAtPath(atlasPath);
                importer.maxTextureSize = maxSize;
                importer.SaveAndReimport();
                var atlasAsset = AssetDatabase.LoadAssetAtPath<Texture2D>(atlasPath);

                var merged = new Material(group.Materials[0]) { name = "Merged " + WPFMAShaderSwap.ShortName(group.Shader.name) };
                merged.mainTexture = atlasAsset;
                merged.mainTextureScale = Vector2.one;
                merged.mainTextureOffset = Vector2.zero;
                if (merged.HasProperty("_Color"))
                    merged.SetColor("_Color", Color.white);

                // Glow (emission) packed the same way, so posters that light up still do.
                if (group.Materials.Any(Emissive))
                {
                    EditorUtility.DisplayProgressBar("Material merger", "Packing the glow textures", 0.55f);
                    if (PackEmission(group.Materials, rects, atlasWidth, atlasHeight, maxSize, folder, merged) == null)
                        merged.DisableKeyword("_EMISSION");
                }
                AssetDatabase.CreateAsset(merged, AssetDatabase.GenerateUniqueAssetPath(folder + "/" + merged.name + ".mat"));

                EditorUtility.DisplayProgressBar("Material merger", "Re-mapping meshes", 0.7f);
                Undo.SetCurrentGroupName("Merge materials");
                int undoGroup = Undo.GetCurrentGroup();
                var meshCache = new Dictionary<KeyValuePair<Mesh, int>, Mesh>();

                foreach (var renderer in group.Renderers)
                {
                    int index = group.Materials.IndexOf(renderer.sharedMaterial);
                    var filter = renderer.GetComponent<MeshFilter>();
                    var key = new KeyValuePair<Mesh, int>(filter.sharedMesh, index);

                    Mesh remapped;
                    if (!meshCache.TryGetValue(key, out remapped))
                    {
                        remapped = UnityEngine.Object.Instantiate(filter.sharedMesh);
                        remapped.name = filter.sharedMesh.name + " (merged)";
                        var rect = rects[index];
                        remapped.uv = remapped.uv.Select(uv => new Vector2(rect.x + uv.x * rect.width, rect.y + uv.y * rect.height)).ToArray();
                        AssetDatabase.CreateAsset(remapped, AssetDatabase.GenerateUniqueAssetPath(folder + "/" + WPFMAPaths.SafeFileName(remapped.name) + ".asset"));
                        meshCache[key] = remapped;
                    }

                    Undo.RecordObject(filter, "Merge materials");
                    Undo.RecordObject(renderer, "Merge materials");
                    filter.sharedMesh = remapped;
                    renderer.sharedMaterial = merged;
                }

                Undo.CollapseUndoOperations(undoGroup);
                AssetDatabase.SaveAssets();

                return "Merged " + group.Materials.Count + " materials into one (" + group.Renderers.Count + " objects). " +
                       "Copies of the meshes and the atlas are in " + folder + "; the originals are untouched.";
            }
            finally
            {
                foreach (var tile in tiles)
                    UnityEngine.Object.DestroyImmediate(tile);
                EditorUtility.ClearProgressBar();
            }
        }
    }

    internal static class WPFMAMaterialMergerSection
    {
        private const string PrefKey = "WPFMA.Tools.MaterialMergerExpanded";
        private static readonly int[] Sizes = { 1024, 2048, 4096 };

        private static WPFMAMaterialMerger.Scan scan;
        private static bool selectionOnly;
        private static int sizeIndex
        {
            get { return Math.Max(0, Array.IndexOf(Sizes, WPFMAToolDefaults.WorldAtlasSize)); }
            set { WPFMAToolDefaults.WorldAtlasSize = Sizes[value]; }
        }
        private static string status;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Atlas maker (material merger)",
                scan == null ? "not scanned yet" : scan.Groups.Count + " group(s) can merge", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Merge materials into one atlas.", "Combines many materials that use the same shader into one, by packing their textures into a single " + "atlas. Static objects that share a material are drawn together, so fewer materials means a faster world."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.LabelField(new GUIContent("Tip: merge posters into one image.", "Lots of posters or pictures? Select them, tick \"Only the selected objects\", scan, then merge. They end up " + "sharing one image, and each one still shows its own picture. Glow (emission) is packed too. Leave out posters " + "an Udon script changes the picture of, since those need their own material."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            EditorGUILayout.Space(4f);

            selectionOnly = EditorGUILayout.ToggleLeft("Only the selected objects", selectionOnly);
            if (GUILayout.Button(scan == null ? "Scan" : "Scan again"))
            {
                bool selection = selectionOnly;
                EditorApplication.delayCall += () =>
                {
                    var renderers = selection
                        ? Selection.gameObjects.Where(g => !EditorUtility.IsPersistent(g)).SelectMany(g => g.GetComponentsInChildren<MeshRenderer>())
                        : UnityEngine.Object.FindObjectsOfType<MeshRenderer>();
                    scan = WPFMAMaterialMerger.Find(renderers.Distinct());
                    status = null;
                };
            }

            if (scan == null)
                return;

            if (scan.Groups.Count == 0)
                EditorGUILayout.LabelField(new GUIContent("Nothing to merge.", "Nothing to merge - no two mergeable materials share a shader."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            foreach (var group in scan.Groups)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    group.Merge = EditorGUILayout.Toggle(group.Merge, GUILayout.Width(16f));
                    EditorGUILayout.LabelField(group.Shader.name, WPFMAToolSection.Hint(WPFMAToolSection.AccentBlue));
                    EditorGUILayout.LabelField(group.Materials.Count + " materials, " + group.Renderers.Count + " objects",
                        WPFMAToolSection.Hint(WPFMAToolSection.FaintText), GUILayout.Width(170f));
                }
            }

            if (scan.Skipped > 0)
            {
                EditorGUILayout.LabelField("Left out: " + string.Join(", ", scan.SkipReasons.Take(4).ToArray()) + " (those cannot share an atlas).",
                    WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            }

            sizeIndex = EditorGUILayout.Popup("Atlas size", sizeIndex, Sizes.Select(s => s.ToString()).ToArray());

            int chosen = scan.Groups.Count(g => g.Merge);
            using (new EditorGUI.DisabledScope(chosen == 0))
            {
                if (GUILayout.Button("Merge " + chosen + " group(s)", GUILayout.Height(26f)))
                {
                    var groups = scan.Groups.Where(g => g.Merge).ToList();
                    int size = Sizes[sizeIndex];
                    EditorApplication.delayCall += () =>
                    {
                        var folders = groups.Select(g => WPFMAWorldTypes.SceneFolder() + "/Merged - " + WPFMAPaths.SafeFileName(WPFMAShaderSwap.ShortName(g.Shader.name))).ToList();
                        var before = folders.Select(WPFMAChangeLog.FilesIn).ToList();
                        status = WPFMAChangeLog.Run("Material merger", "Merge " + groups.Count + " group(s)", null, true,
                            () => string.Join("\n", groups.Select(g => WPFMAMaterialMerger.Merge(g, size)).ToArray()),
                            () => folders.SelectMany((f, i) => WPFMAChangeLog.NewFiles(f, before[i])));
                        scan = null;
                    };
                }
            }

            EditorGUILayout.LabelField(new GUIContent("Main texture and colour only.", "Only the main texture and colour are merged - normal maps and other textures come from the first material. " + "Works best for props sharing a simple shader. Ctrl+Z puts the old materials back."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

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