package cn.ibizlab.codegen.config;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DynamicParamUtils {
    private static final String DYNAMIC_PARAM_PREFIX = "${";
    private static final String DYNAMIC_PARAM_SUFFIX = "}";

    public static Object processObject(Object content) {
        if(ObjectUtils.isEmpty(content))
            return content;
        else if(content instanceof String)
            return process(content.toString());
        else if(content instanceof List && ((List) content).get(0) instanceof String) {
            return process((List)content);
        }
        return content;
    }

    public static String process(String content) {
        return processDynamicParams(content,System.getenv());
    }

    public static List<String> process(List<String> content) {
        if(content==null)
            return null;
        List<String> rt=new ArrayList<>();
        content.forEach(item->{
            rt.add(process(item));
        });
        return rt;
    }


	// 多变量，data 为 key - value 形式
    public static String processDynamicParams(String content, Map data) {
        if(content==null)
            return null;
        int begin = content.indexOf(DYNAMIC_PARAM_PREFIX);
        int end = content.indexOf(DYNAMIC_PARAM_SUFFIX);
        if (begin == -1 || end == -1 || begin > end) {
            return content;
        }
        String startContent = content.substring(0, begin);
        String substring = content.substring(begin, end + 1);
        if (StringUtils.isNotEmpty(substring)) {
            String key = substring.replace("${", "").replace("}", "");
            String[] pairs=key.split(":");
            String defaultValue=null;
            if(pairs.length>1)
            {
                key=pairs[0];
                defaultValue=pairs[1];
            }
            Object value = data.get(key);
            if(ObjectUtils.isEmpty(value))
                value=data.getOrDefault(key.toUpperCase(),defaultValue);
            if (value != null) {
                startContent = startContent + value.toString();
            } else {
                startContent += substring;
            }
        }

        int length = content.length();
        if ( length == end + 1) {
            return startContent;
        } else {
            return startContent + processDynamicParams(content.substring(end + 1, length), data);
        }
    }
}
