package ink.wgink.common.manager.env;

import ink.wgink.common.dao.env.IEnvDao;
import ink.wgink.common.pojo.Env;
import ink.wgink.common.pojo.dtos.env.EnvDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * @ClassName: EnvManager
 * @Description: 环境变量管理
 * @Author: wanggeng
 * @Date: 2022/5/16 10:47
 * @Version: 1.0
 */
public class EnvManager {

    private static final Logger LOG = LoggerFactory.getLogger(EnvManager.class);
    private static EnvManager envManager = EnvManagerBuilder.envManager;
    private static Pattern ENV_VARIABLE = Pattern.compile("%[a-zA-Z\\d\\_\\-]+%");
    private IEnvDao envDao;
    private Env env = new Env();

    private EnvManager() {}

    public static EnvManager getInstance() {
        return envManager;
    }

    /**
     * 刷新环境变量
     */
    public void refreshEnv() {
        env.clear();
        List<EnvDTO> envDTOS = envDao.list();
        envDTOS.forEach(envDTO -> {
            env.put(envDTO.getEnvKey(), envDTO.getEnvValue());
        });
    }

    /**
     * 获得环境变量
     *
     * @return
     */
    public Env getEnv() {
        return env;
    }

    public boolean isKeyExist(String key) {
        return env.containsKey(key);
    }

    public String getValue(String key) {
        String value = env.get(key);
        value = value == null ? "" : value;
        // 替换变量
        Matcher matcher = ENV_VARIABLE.matcher(value);
        while (matcher.find()) {
            String variable = matcher.group();
            String variableValue = env.get(variable.substring(1, variable.length() - 1));
            if (StringUtils.isBlank(variableValue)) {
                continue;
            }
            value = value.replaceFirst(variable, variableValue);
        }
        return value;
    }

    public void setEnvDao(IEnvDao envDao) {
        this.envDao = envDao;
    }

    private static class EnvManagerBuilder {
        public static final EnvManager envManager = new EnvManager();
    }

}
