import lombok.experimental.UtilityClass;
import org.springframework.cglib.beans.BeanMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 10/11/2022 11:02 上午
 * 描述:
 *
 * @author grant
 */
@UtilityClass
public class TemplateUtils {
    /**
     * 变量占位符匹配正则
     */
    private static final Pattern pattern = Pattern.compile("(\\$\\{(.*?)})");

    /**
     * 解析
     *
     * @param templateStr 模板str
     * @param bean        豆
     * @return {@link String}
     */
    public String parse(String templateStr, Object bean){
        if (!templateStr.contains("$")){
            return templateStr;
        }
        return parse(templateStr, BeanMap.create(bean));
    }

    /**
     * 解析
     *
     * @param templateStr 模板str
     * @param params      参数
     * @return {@link String}
     */
    public String parse(String templateStr, Map<String, Object> params){
        if (!templateStr.contains("$")){
            return templateStr;
        }

        String template = templateStr;
        Map<String, String> variableMap = getVariableMap(template);
        Set<Map.Entry<String, String>> entries = variableMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (params.containsKey(key)){
                template = template.replace(value, String.valueOf(params.get(key)));
            }
        }
        return template;
    }

    /**
     * 解析变量名
     *
     * @param templateStr 模板str
     * @return {@link List}<{@link String}>
     */
    public List<String> parseVariableNames(String templateStr){
        return new ArrayList<>(getVariableMap(templateStr).keySet());
    }

    /**
     * 获取变量映射
     *
     * @param templateStr 模板str
     * @return {@link Map}<{@link String}, {@link String}>
     */
    private Map<String, String> getVariableMap(String templateStr) {
        Matcher matcher = pattern.matcher(templateStr);
        Map<String, String> variableMap = new HashMap<>();
        while (matcher.find()) {
            variableMap.put(matcher.group(2).trim(), matcher.group(1));
        }
        return variableMap;
    }
}