using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;

public class AssetBatchRenamer : EditorWindow
{
    int removeFrontCount = 0;
    int removeBackCount = 0;
    string prefixToAdd = "";
    string suffixToAdd = "";

    [MenuItem("Tools/Asset Batch Renamer")]
    public static void ShowWindow()
    {
        GetWindow<AssetBatchRenamer>("Asset Batch Renamer");
    }

    void OnGUI()
    {
        GUILayout.Label("선택한 에셋 이름 일괄 수정", EditorStyles.boldLabel);

        removeFrontCount = EditorGUILayout.IntField("앞에서 제거할 문자 수", removeFrontCount);
        removeBackCount = EditorGUILayout.IntField("뒤에서 제거할 문자 수", removeBackCount);
        prefixToAdd = EditorGUILayout.TextField("앞에 추가할 문자열", prefixToAdd);
        suffixToAdd = EditorGUILayout.TextField("뒤에 추가할 문자열", suffixToAdd);

        if (GUILayout.Button("선택된 에셋 이름 변경"))
        {
            RenameSelectedAssets();
        }
    }

    void RenameSelectedAssets()
    {
        Object[] selectedObjects = Selection.objects;
        Dictionary<string, int> nameConflictMap = new Dictionary<string, int>();

        Undo.RecordObjects(selectedObjects, "Batch Rename Assets");

        foreach (Object obj in selectedObjects)
        {
            string assetPath = AssetDatabase.GetAssetPath(obj);
            string assetName = Path.GetFileNameWithoutExtension(assetPath);
            string assetExtension = Path.GetExtension(assetPath);
            string assetDir = Path.GetDirectoryName(assetPath);

            string newName = assetName;

            // 앞 문자 제거
            if (removeFrontCount > 0 && newName.Length > removeFrontCount)
                newName = newName.Substring(removeFrontCount);

            // 뒤 문자 제거
            if (removeBackCount > 0 && newName.Length > removeBackCount)
                newName = newName.Substring(0, newName.Length - removeBackCount);

            // 앞뒤 추가
            newName = prefixToAdd + newName + suffixToAdd;

            // 이름 충돌 방지 처리
            string finalName = newName;
            int counter = 1;
            while (AssetExists(assetDir, finalName, assetExtension) && finalName != assetName)
            {
                finalName = newName + "_" + counter;
                counter++;
            }

            if (finalName != assetName)
            {
                string result = AssetDatabase.RenameAsset(assetPath, finalName);
                if (!string.IsNullOrEmpty(result))
                {
                    Debug.LogWarning($"[{obj.name}] 이름 변경 실패: {result}");
                }
            }
        }

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }

    bool AssetExists(string directory, string name, string extension)
    {
        string fullPath = Path.Combine(directory, name + extension).Replace("\\", "/");
        return AssetDatabase.LoadAssetAtPath<Object>(fullPath) != null;
    }
}
