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

namespace WPFMA
{
    internal static class WPFMAShaderSwap
    {
        internal sealed class Entry
        {
            public Material Material;
            public bool Swap = true;
            public int Uses;
        }

        private static readonly string[][] QuickPatterns =
        {
            new[] { "VRChat/Mobile/Toon Lit" },
            new[] { "VRChat/Mobile/Standard Lite" },
            new[] { "lilToon" },
            new[] { "/Poiyomi Toon", "Poiyomi Toon" },
            new[] { "Standard" }
        };

        private static List<string> quickShaders;

        internal static List<string> QuickShaders()
        {
            if (quickShaders != null)
                return quickShaders;

            var names = ShaderUtil.GetAllShaderInfo()
                .Where(i => !i.hasErrors && !i.name.StartsWith("Hidden/") && !i.name.StartsWith("Legacy Shaders/"))
                .Select(i => i.name)
                .ToList();

            quickShaders = new List<string>();
            foreach (var patterns in QuickPatterns)
            {
                string exact = names.FirstOrDefault(n => n == patterns[0]);
                string found = exact ?? names.Where(n => patterns.Any(p => n.EndsWith(p, StringComparison.Ordinal)))
                    .OrderByDescending(n => n)
                    .FirstOrDefault();

                if (found != null && !quickShaders.Contains(found))
                    quickShaders.Add(found);
            }

            return quickShaders;
        }

        internal static List<Entry> Collect(GameObject root)
        {
            var entries = new Dictionary<Material, Entry>();
            if (root == null)
                return new List<Entry>();

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

                    Entry entry;
                    if (!entries.TryGetValue(material, out entry))
                    {
                        entry = new Entry { Material = material };
                        entries.Add(material, entry);
                    }

                    entry.Uses++;
                }
            }

            return entries.Values.OrderBy(e => e.Material.shader != null ? e.Material.shader.name : string.Empty)
                .ThenBy(e => e.Material.name)
                .ToList();
        }

        internal static string Swap(GameObject root, List<Entry> entries, Shader shader, bool makeCopies)
        {
            var chosen = entries.Where(e => e.Swap && e.Material != null).ToList();
            if (chosen.Count == 0 || shader == null)
                return "Nothing to swap.";

            Undo.SetCurrentGroupName("Swap shaders");
            int group = Undo.GetCurrentGroup();

            var replacements = new Dictionary<Material, Material>();
            string folder = null;

            if (makeCopies)
            {
                bool world = WPFMA.Editor.WPFMAInstaller.PanelKind == WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds;
                folder = (world ? WPFMAWorldTypes.SceneFolder() : WPFMAAvatarFolders.For(root)) + "/Materials - " +
                         WPFMAPaths.SafeFileName(ShortName(shader.name));
                WPFMAAvatarFolders.Ensure(folder);
            }

            foreach (var entry in chosen)
            {
                var source = entry.Material;
                Material target;

                if (makeCopies)
                {
                    target = new Material(source) { name = source.name };
                    string path = AssetDatabase.GenerateUniqueAssetPath(folder + "/" + WPFMAPaths.SafeFileName(source.name) + ".mat");
                    AssetDatabase.CreateAsset(target, path);
                }
                else
                {
                    target = source;
                    Undo.RecordObject(target, "Swap shaders");
                }

                Convert(source, target, shader);
                replacements[source] = target;
            }

            if (makeCopies)
            {
                foreach (var renderer in root.GetComponentsInChildren<Renderer>(true))
                {
                    var materials = renderer.sharedMaterials;
                    bool changed = false;

                    for (int i = 0; i < materials.Length; i++)
                    {
                        Material replacement;
                        if (materials[i] != null && replacements.TryGetValue(materials[i], out replacement))
                        {
                            materials[i] = replacement;
                            changed = true;
                        }
                    }

                    if (!changed)
                        continue;

                    Undo.RecordObject(renderer, "Swap shaders");
                    renderer.sharedMaterials = materials;
                    PrefabUtility.RecordPrefabInstancePropertyModifications(renderer);
                }
            }

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

            return "Swapped " + chosen.Count + " material(s) to " + shader.name +
                   (makeCopies ? ". Copies are in " + folder + "; the originals are untouched." : ".");
        }

        private static void Convert(Material source, Material target, Shader shader)
        {
            var mainTexture = source.mainTexture;
            var scale = source.HasProperty("_MainTex") ? source.mainTextureScale : Vector2.one;
            var offset = source.HasProperty("_MainTex") ? source.mainTextureOffset : Vector2.zero;
            var color = Read(source, "_Color", "_BaseColor");
            var normal = Texture(source, "_BumpMap", "_NormalMap");
            var emissionMap = Texture(source, "_EmissionMap");
            var emissionColor = Read(source, "_EmissionColor");
            float? cutoff = source.HasProperty("_Cutoff") ? source.GetFloat("_Cutoff") : (float?)null;

            target.shader = shader;
            target.shaderKeywords = new string[0];
            target.renderQueue = -1;

            if (mainTexture != null)
            {
                target.mainTexture = mainTexture;
                if (target.HasProperty("_MainTex"))
                {
                    target.mainTextureScale = scale;
                    target.mainTextureOffset = offset;
                }
            }

            if (color.HasValue)
            {
                if (target.HasProperty("_Color"))
                    target.SetColor("_Color", color.Value);
                if (target.HasProperty("_BaseColor"))
                    target.SetColor("_BaseColor", color.Value);
            }

            if (normal != null)
            {
                if (target.HasProperty("_BumpMap"))
                    target.SetTexture("_BumpMap", normal);
                if (target.HasProperty("_NormalMap"))
                    target.SetTexture("_NormalMap", normal);
            }

            if (emissionMap != null && target.HasProperty("_EmissionMap"))
                target.SetTexture("_EmissionMap", emissionMap);
            if (emissionColor.HasValue && target.HasProperty("_EmissionColor"))
                target.SetColor("_EmissionColor", emissionColor.Value);
            if (cutoff.HasValue && target.HasProperty("_Cutoff"))
                target.SetFloat("_Cutoff", cutoff.Value);

            try
            {
                MaterialEditor.ApplyMaterialPropertyDrawers(target);
            }
            catch (Exception)
            {
            }

            EditorUtility.SetDirty(target);
        }

        private static Color? Read(Material material, params string[] names)
        {
            foreach (var name in names)
                if (material.HasProperty(name))
                    return material.GetColor(name);
            return null;
        }

        private static Texture Texture(Material material, params string[] names)
        {
            foreach (var name in names)
                if (material.HasProperty(name) && material.GetTexture(name) != null)
                    return material.GetTexture(name);
            return null;
        }

        internal static string ShortName(string shaderName)
        {
            int slash = shaderName.LastIndexOf('/');
            return slash >= 0 ? shaderName.Substring(slash + 1) : shaderName;
        }
    }

    internal static class WPFMAShaderSwapSection
    {
        private const string PrefKey = "WPFMA.Tools.ShaderSwapExpanded";

        private static GameObject root;
        private static List<WPFMAShaderSwap.Entry> entries;
        private static Shader target;
        private static bool makeCopies { get { return WPFMAToolDefaults.ShaderSwapCopies; } set { WPFMAToolDefaults.ShaderSwapCopies = value; } }
        private static string status;
        private static Vector2 scroll;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Bulk shader swap", Detail(), PrefKey, Body);
        }

        private static string Detail()
        {
            return entries == null || root == null ? "nothing selected" : entries.Count + " material(s)";
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Swap every material's shader.", "Switches every material on the avatar to another shader in one go - for example to VRChat's mobile " + "shaders for a Quest version - keeping the main texture, colour, normal map and emission."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            bool world = WPFMA.Editor.WPFMAInstaller.PanelKind == WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds;
            var active = Selection.activeGameObject;
            var selected = world
                ? (active != null && !EditorUtility.IsPersistent(active) ? active : null)
                : WPFMAAvatarFolders.AvatarRoot(active);
            if (selected != root || entries == null)
            {
                root = selected;
                entries = WPFMAShaderSwap.Collect(root);
                status = null;
            }

            if (root == null)
            {
                EditorGUILayout.LabelField(world
                        ? "Select an object in the Hierarchy - everything under it is included. Pick a parent to do a whole area."
                        : "Select the avatar in the Hierarchy.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField(world ? "Under" : "Avatar", root.name, EditorStyles.boldLabel);
                if (GUILayout.Button("Refresh", GUILayout.Width(80f)))
                    entries = WPFMAShaderSwap.Collect(root);
            }

            target = (Shader)EditorGUILayout.ObjectField("Swap to", target, typeof(Shader), false);

            var quick = WPFMAShaderSwap.QuickShaders();
            if (quick.Count > 0)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    GUILayout.Space(EditorGUIUtility.labelWidth);
                    foreach (var name in quick)
                    {
                        if (GUILayout.Button(WPFMAShaderSwap.ShortName(name), EditorStyles.miniButton))
                            target = Shader.Find(name);
                    }
                }
            }

            if (target != null && target.name.StartsWith("VRChat/Mobile/"))
            {
                EditorGUILayout.LabelField(new GUIContent("Quest needs VRChat/Mobile shaders.", "VRChat's mobile shaders are what Quest supports. Do this on a copy of the avatar (or with " + "EasyQuestSwitch) so your PC version keeps its shaders."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            }

            makeCopies = EditorGUILayout.ToggleLeft(new GUIContent("Make copies of the materials", "Keep the originals untouched."), makeCopies);
            if (!makeCopies)
            {
                EditorGUILayout.LabelField(new GUIContent("Changes the material files themselves.", "The material files themselves will change - anything else using them changes too."), WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
            }

            EditorGUILayout.Space(4f);
            using (new EditorGUILayout.HorizontalScope())
            {
                if (GUILayout.Button("All", EditorStyles.miniButton, GUILayout.Width(40f)))
                    entries.ForEach(e => e.Swap = true);
                if (GUILayout.Button("None", EditorStyles.miniButton, GUILayout.Width(44f)))
                    entries.ForEach(e => e.Swap = false);
            }

            scroll = EditorGUILayout.BeginScrollView(scroll, GUILayout.MaxHeight(260f));
            string lastShader = null;
            foreach (var entry in entries)
            {
                if (entry.Material == null)
                    continue;

                string shaderName = entry.Material.shader != null ? entry.Material.shader.name : "(no shader)";
                if (shaderName != lastShader)
                {
                    lastShader = shaderName;
                    using (new EditorGUILayout.HorizontalScope())
                    {
                        EditorGUILayout.LabelField(shaderName, WPFMAToolSection.Hint(WPFMAToolSection.AccentBlue));
                        if (GUILayout.Button("only these", EditorStyles.miniButton, GUILayout.Width(70f)))
                        {
                            string only = shaderName;
                            entries.ForEach(e => e.Swap = e.Material != null && e.Material.shader != null && e.Material.shader.name == only);
                        }
                    }
                }

                using (new EditorGUILayout.HorizontalScope())
                {
                    GUILayout.Space(12f);
                    entry.Swap = EditorGUILayout.Toggle(entry.Swap, GUILayout.Width(16f));
                    EditorGUILayout.ObjectField(entry.Material, typeof(Material), false);
                    EditorGUILayout.LabelField(entry.Uses + "x", WPFMAToolSection.Hint(WPFMAToolSection.FaintText), GUILayout.Width(30f));
                }
            }
            EditorGUILayout.EndScrollView();

            int count = entries.Count(e => e.Swap);
            using (new EditorGUI.DisabledScope(target == null || count == 0))
            {
                if (GUILayout.Button(target == null ? "Pick a shader to swap to" : "Swap " + count + " material(s) to " + WPFMAShaderSwap.ShortName(target.name),
                        GUILayout.Height(26f)))
                {
                    var shader = target;
                    var avatar = root;
                    var list = entries;
                    bool copies = makeCopies;
                    EditorApplication.delayCall += () =>
                    {
                        bool worldMode = WPFMA.Editor.WPFMAInstaller.PanelKind == WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds;
                        string folder = (worldMode ? WPFMAWorldTypes.SceneFolder() : WPFMAAvatarFolders.For(avatar)) + "/Materials - " +
                                        WPFMAPaths.SafeFileName(WPFMAShaderSwap.ShortName(shader.name));
                        var before = WPFMAChangeLog.FilesIn(folder);
                        var touched = copies ? null : WPFMAChangeLog.AssetPaths(list.Where(e => e.Swap).Select(e => (UnityEngine.Object)e.Material)).ToList();
                        status = WPFMAChangeLog.Run("Bulk shader swap", "Swap to " + shader.name, touched, true,
                            () => WPFMAShaderSwap.Swap(avatar, list, shader, copies), () => WPFMAChangeLog.NewFiles(folder, before));
                        entries = WPFMAShaderSwap.Collect(avatar);
                        Debug.Log("[WPFMA-SDK] " + status);
                    };
                }
            }

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