package com.yeejoin.amos.boot.biz.common.utils;

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

/**
 * @description: 驼峰工具类
 * @author: duanwei
 * @create: 2020-05-28 13:57
 **/
public class NameUtils {
    private static Pattern NUMBER_PATTERN = Pattern.compile("([A-Za-z\\d]+)(_)?");
    private static Pattern AZTEXT_PATTERN = Pattern.compile("[A-Z]([a-z\\d]+)?");

    /**
     * 下划线转驼峰法(默认小驼峰)
     *
     * @param line       源字符串
     * @param smallCamel 大小驼峰,是否为小驼峰(驼峰，第一个字符是大写还是小写)
     * @return 转换后的字符串
     */
    public static String underline2Camel(String line, boolean... smallCamel) {
        if (line == null || line.isEmpty()) {
            return "";
        }

        // 如果包含下划线，执行下划线转驼峰逻辑
        if (line.contains("_")) {
            StringBuffer sb = new StringBuffer();
            Matcher matcher = NUMBER_PATTERN.matcher(line);
            while (matcher.find()) {
                String word = matcher.group();
                if ((smallCamel.length == 0 || smallCamel[0]) && matcher.start() == 0) {
                    sb.append(Character.toLowerCase(word.charAt(0)));
                } else {
                    sb.append(Character.toUpperCase(word.charAt(0)));
                }
                int index = word.lastIndexOf('_');
                if (index > 0) {
                    sb.append(word.substring(1, index).toLowerCase());
                } else {
                    sb.append(word.substring(1).toLowerCase());
                }
            }
            return sb.toString();
        }

        // 如果没有下划线但是全大写（例如 STOREY），按驼峰规则转换
        if (line.equals(line.toUpperCase())) {
            if (smallCamel.length == 0 || smallCamel[0]) {
                return line.substring(0, 1).toLowerCase() + line.substring(1).toLowerCase();
            } else {
                return line.substring(0, 1).toUpperCase() + line.substring(1).toLowerCase();
            }
        }

        // 否则（已是驼峰格式等），直接返回
        return line;
    }


    /**
     * 驼峰法转下划线
     *
     * @param line 源字符串
     * @return 转换后的字符串
     */
    public static String camel2Underline(String line) {
        if (line == null || "".equals(line)) {
            return "";
        }
        line = String.valueOf(line.charAt(0)).toUpperCase()
                .concat(line.substring(1));
        StringBuffer sb = new StringBuffer();
        Matcher matcher = AZTEXT_PATTERN.matcher(line);
        while (matcher.find()) {
            String word = matcher.group();
            sb.append(word.toUpperCase());
            sb.append(matcher.end() == line.length() ? "" : "_");
        }
        return sb.toString();
    }
}
