package com.lanyuanxiaoyao.service.cli.runner;

import cn.hutool.core.util.ObjectUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * spring boot 配置文件转义
 *
 * @author lanyuanxiaoyao
 * @date 2024-02-25
 */
public class SpringPropertiesEscapeHelper {
    public static <T> Map<String, T> escapeMap(Map<String, T> map) {
        return escapeMapValue(escapeMapKey(map));
    }
    /**
     * 使用 _ 代替 map key 的 .
     */
    public static <T> Map<String, T> escapeMapKey(Map<String, T> map) {
        if (ObjectUtil.isEmpty(map)) {
            return map;
        }
        Map<String, T> result = new HashMap<>();
        for (Map.Entry<String, T> entry : map.entrySet()) {
            result.put(entry.getKey().replaceAll("_", "."), entry.getValue());
        }
        return result;
    }

    public static <T> Map<String, T> escapeMapValue(Map<String, T> map) {
        // https://github.com/spring-projects/spring-framework/issues/9628
        // spring boot 的配置文件没有办法转义 $，使用 $\{ -> ${ 来绕过一下
        if (ObjectUtil.isEmpty(map)) {
            return map;
        }
        return map.entrySet()
                .stream()
                .peek(entry -> {
                    if (entry.getValue() instanceof String) {
                        String value = (String) entry.getValue();
                        //noinspection unchecked
                        entry.setValue((T) value.replace("$\\{", "${"));
                    }
                })
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }
}
