// 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 System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

namespace WPFMA
{
    /// <summary>Renames many selected objects (Hierarchy) or assets (Project) at once, with a preview first.</summary>
    internal static class WPFMARenamer
    {
        internal enum Casing
        {
            Keep,
            Lower,
            Upper,
            Title
        }

        internal sealed class Options
        {
            public string Find = string.Empty;
            public string Replace = string.Empty;
            public bool MatchCase;
            public string BaseName = string.Empty;
            public string Prefix = string.Empty;
            public string Suffix = string.Empty;
            public bool Number;
            public int Start = 1;
            public int Digits = 2;
            public string Separator = "_";
            public bool CleanCopies = true;
            public Casing Case;
        }

        /// <summary>A target's new name: copies cleaned, find/replace, base name, case, prefix and suffix, then the number.</summary>
        internal static string NewName(string name, int index, Options o)
        {
            string result = name;
            if (o.CleanCopies)
                result = Regex.Replace(result, @"(\s*\(\d+\)|\.\d{3})$", string.Empty);
            if (!string.IsNullOrEmpty(o.Find))
                result = Regex.Replace(result, Regex.Escape(o.Find), (o.Replace ?? string.Empty).Replace("$", "$$"),
                    o.MatchCase ? RegexOptions.None : RegexOptions.IgnoreCase);
            if (!string.IsNullOrEmpty(o.BaseName))
                result = o.BaseName;

            switch (o.Case)
            {
                case Casing.Lower:
                    result = result.ToLowerInvariant();
                    break;
                case Casing.Upper:
                    result = result.ToUpperInvariant();
                    break;
                case Casing.Title:
                    result = Regex.Replace(result.ToLowerInvariant(), @"(^|[\s_\-.])([a-z])", m => m.Groups[1].Value + m.Groups[2].Value.ToUpperInvariant());
                    break;
            }

            result = (o.Prefix ?? string.Empty) + result + (o.Suffix ?? string.Empty);
            if (o.Number)
                result += (o.Separator ?? string.Empty) + (o.Start + index).ToString("D" + Mathf.Clamp(o.Digits, 1, 6));
            return result;
        }

        /// <summary>The selected scene objects in Hierarchy order (top to bottom), so numbers follow what you see.</summary>
        internal static List<GameObject> SelectedObjects()
        {
            return Selection.gameObjects.Where(g => g != null && !EditorUtility.IsPersistent(g))
                .OrderBy(g => g.scene.handle)
                .ThenBy(g => HierarchyKey(g.transform), StringComparer.Ordinal)
                .ToList();
        }

        private static string HierarchyKey(Transform t)
        {
            var parts = new List<string>();
            for (; t != null; t = t.parent)
                parts.Insert(0, t.GetSiblingIndex().ToString("D6"));
            return string.Join("/", parts.ToArray());
        }

        /// <summary>The selected assets in the Project, by path.</summary>
        internal static List<string> SelectedAssets()
        {
            return Selection.assetGUIDs.Select(AssetDatabase.GUIDToAssetPath)
                .Where(p => !string.IsNullOrEmpty(p) && p.StartsWith("Assets/", StringComparison.Ordinal))
                .OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
                .ToList();
        }

        internal static string RenameObjects(List<GameObject> objects, Options o)
        {
            Undo.RecordObjects(objects.Cast<UnityEngine.Object>().ToArray(), "Rename");
            int changed = 0;
            for (int i = 0; i < objects.Count; i++)
            {
                string name = NewName(objects[i].name, i, o);
                if (name == objects[i].name || string.IsNullOrEmpty(name))
                    continue;
                objects[i].name = name;
                changed++;
            }
            return "Renamed " + changed + " object(s). Ctrl+Z puts the old names back.";
        }

        /// <summary>The last asset rename, so it can be put back (Unity's Undo doesn't cover asset renames).</summary>
        internal static readonly List<KeyValuePair<string, string>> LastAssetRenames = new List<KeyValuePair<string, string>>();

        internal static string RenameAssets(List<string> paths, Options o)
        {
            LastAssetRenames.Clear();
            var problems = new List<string>();
            int changed = 0;
            for (int i = 0; i < paths.Count; i++)
            {
                string oldName = Path.GetFileNameWithoutExtension(paths[i]);
                string name = NewName(oldName, i, o);
                if (name == oldName || string.IsNullOrEmpty(name))
                    continue;
                string error = AssetDatabase.RenameAsset(paths[i], name);
                if (!string.IsNullOrEmpty(error))
                {
                    problems.Add(oldName + ": " + error);
                    continue;
                }
                string newPath = Path.GetDirectoryName(paths[i]).Replace('\\', '/') + "/" + name + Path.GetExtension(paths[i]);
                LastAssetRenames.Add(new KeyValuePair<string, string>(newPath, oldName));
                changed++;
            }
            return "Renamed " + changed + " asset(s)." + (problems.Count > 0 ? " Couldn't rename " + problems.Count + ": " + problems[0] : string.Empty);
        }

        internal static string PutBackAssets()
        {
            int changed = 0;
            foreach (var pair in LastAssetRenames.AsEnumerable().Reverse())
                if (string.IsNullOrEmpty(AssetDatabase.RenameAsset(pair.Key, pair.Value)))
                    changed++;
            LastAssetRenames.Clear();
            return "Put back " + changed + " asset name(s).";
        }
    }

    internal static class WPFMARenamerSection
    {
        private const string PrefKey = "WPFMA.Tools.RenamerExpanded";
        private static readonly WPFMARenamer.Options Options = new WPFMARenamer.Options();
        private static string status;

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

        private static string Detail()
        {
            int objects = WPFMARenamer.SelectedObjects().Count;
            if (objects > 0)
                return objects + " object(s) selected";
            int assets = WPFMARenamer.SelectedAssets().Count;
            return assets > 0 ? assets + " asset(s) selected" : "nothing selected";
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Rename many things at once.",
                    "Select objects in the Hierarchy or assets in the Project. Find and replace, a new base name, prefix and suffix, " +
                    "numbering and case - with a preview before anything changes."),
                WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            var objects = WPFMARenamer.SelectedObjects();
            var assets = objects.Count > 0 ? new List<string>() : WPFMARenamer.SelectedAssets();
            var names = objects.Count > 0 ? objects.Select(g => g.name).ToList() : assets.Select(Path.GetFileNameWithoutExtension).ToList();

            float labelWidth = EditorGUIUtility.labelWidth;
            EditorGUIUtility.labelWidth = 70f;
            using (new EditorGUILayout.HorizontalScope())
            {
                Options.Find = EditorGUILayout.TextField("Find", Options.Find);
                Options.Replace = EditorGUILayout.TextField("Replace", Options.Replace);
            }
            using (new EditorGUILayout.HorizontalScope())
            {
                Options.Prefix = EditorGUILayout.TextField("Prefix", Options.Prefix);
                Options.Suffix = EditorGUILayout.TextField("Suffix", Options.Suffix);
            }
            Options.BaseName = EditorGUILayout.TextField(new GUIContent("New name", "Empty keeps each name."), Options.BaseName);
            using (new EditorGUILayout.HorizontalScope())
            {
                Options.Number = EditorGUILayout.ToggleLeft("Number", Options.Number, GUILayout.Width(70f));
                using (new EditorGUI.DisabledScope(!Options.Number))
                {
                    Options.Start = EditorGUILayout.IntField("from", Options.Start, GUILayout.MinWidth(100f));
                    Options.Digits = Mathf.Clamp(EditorGUILayout.IntField("digits", Options.Digits, GUILayout.MinWidth(100f)), 1, 6);
                    Options.Separator = EditorGUILayout.TextField("after", Options.Separator, GUILayout.MinWidth(100f));
                }
            }
            using (new EditorGUILayout.HorizontalScope())
            {
                Options.Case = (WPFMARenamer.Casing)EditorGUILayout.EnumPopup("Case", Options.Case);
                Options.MatchCase = EditorGUILayout.ToggleLeft(new GUIContent("Match case", "Find only matches the same capitals."), Options.MatchCase, GUILayout.Width(100f));
            }
            Options.CleanCopies = EditorGUILayout.ToggleLeft(new GUIContent("Remove copy endings", "Takes ' (1)' and '.001' off the end of names."), Options.CleanCopies);
            EditorGUIUtility.labelWidth = labelWidth;

            if (names.Count == 0)
            {
                EditorGUILayout.LabelField("Select objects or assets.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            }
            else
            {
                EditorGUILayout.Space(4f);
                int changes = 0;
                for (int i = 0; i < names.Count; i++)
                {
                    string after = WPFMARenamer.NewName(names[i], i, Options);
                    if (after != names[i])
                        changes++;
                    if (i < 8)
                        EditorGUILayout.LabelField(names[i] + "  →  " + after,
                            WPFMAToolSection.Hint(after == names[i] ? WPFMAToolSection.FaintText : WPFMAToolSection.MetaText));
                }
                if (names.Count > 8)
                    EditorGUILayout.LabelField("and " + (names.Count - 8) + " more.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

                using (new EditorGUI.DisabledScope(changes == 0))
                {
                    if (GUILayout.Button("Rename " + changes + (objects.Count > 0 ? " object(s)" : " asset(s)"), GUILayout.Height(24f)))
                    {
                        var options = Options;
                        EditorApplication.delayCall += () =>
                            status = objects.Count > 0 ? WPFMARenamer.RenameObjects(objects, options) : WPFMARenamer.RenameAssets(assets, options);
                    }
                }
            }

            if (WPFMARenamer.LastAssetRenames.Count > 0 && GUILayout.Button("Put the last asset names back", EditorStyles.miniButton, GUILayout.Width(200f)))
                status = WPFMARenamer.PutBackAssets();

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