package com.njzscloud.common.core.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StrUtil {
    // 匹配非特殊字符的正则表达式，对应 TS 中的 [^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+
    private static final Pattern SPLIT_CHAR_PATTERN = Pattern.compile("[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+");

    // 匹配大写字母的正则表达式，用于分割单词
    private static final Pattern UPPER_CASE_PATTERN = Pattern.compile("([A-Z])");

    /**
     * 检查字符串是否为空
     */
    private static boolean isBlank(String str) {
        return str == null || str.trim().isEmpty();
    }

    /**
     * 首字母大写
     */
    private static String capitalize(String word) {
        if (isBlank(word)) {
            return word;
        }
        return Character.toUpperCase(word.charAt(0)) +
            (word.length() > 1 ? word.substring(1).toLowerCase() : "");
    }

    /**
     * 以大写字母为分割符，转换成其他分隔符
     */
    public static String processWords(String str, WordJoiner joiner) {
        if (isBlank(str)) {
            return "";
        }

        // 处理字符串：在大写字母前添加分隔符，然后转为小写
        String processed = UPPER_CASE_PATTERN.matcher(str).replaceAll(" $1").toLowerCase();

        // 提取匹配的单词
        Matcher matcher = SPLIT_CHAR_PATTERN.matcher(processed);
        List<String> words = new ArrayList<>();
        while (matcher.find()) {
            words.add(matcher.group().trim());
        }

        // 使用 joiner 连接单词
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < words.size(); i++) {
            result.append(joiner.join(words.get(i), i));
        }
        return result.toString();
    }

    /**
     * 小驼峰命名 (camelCase)
     */
    public static String camelCase(String str) {
        return processWords(str, (word, index) -> {
            if (index == 0) {
                return word;
            } else {
                return capitalize(word);
            }
        });
    }

    /**
     * 大驼峰命名 (PascalCase)
     */
    public static String pascalCase(String str) {
        String camel = camelCase(str);
        return capitalize(camel);
    }

    /**
     * 下划线命名 (snake_case)
     */
    public static String snakeCase(String str) {
        return processWords(str, (word, index) -> {
            if (index == 0) {
                return word;
            } else {
                return "_" + word;
            }
        });
    }

    /**
     * 中横杠命名 (kebab-case)
     */
    public static String kebabCase(String str) {
        return processWords(str, (word, index) -> {
            if (index == 0) {
                return word;
            } else {
                return "-" + word;
            }
        });
    }

    /**
     * 函数式接口，用于处理单词连接
     */
    @FunctionalInterface
    public interface WordJoiner {
        String join(String word, int index);
    }
}
