package ink.wgink.login.base.manager;

import ink.wgink.exceptions.SearchException;
import ink.wgink.interfaces.manager.ISystemConfigManager;
import ink.wgink.login.base.dao.config.IConfigDao;
import ink.wgink.login.base.pojo.dtos.config.ConfigDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: ConfigManager
 * @Description: 系统配置管理
 * @Author: WangGeng
 * @Date: 2019/11/20 10:34
 * @Version: 1.0
 **/
public class ConfigManager implements ISystemConfigManager {

    private static final Logger LOG = LoggerFactory.getLogger(ConfigManager.class);
    private static ConfigManager configManager = ConfigManagerBuilder.configManager;
    private IConfigDao configDao;
    private Map<String, String> config;
    public static final String SYSTEM_LICENSE = "systemLicense";
    public static final String CONFIG_KEY = "configKey";
    public static final String CONFIG_VALUE = "configValue";

    private ConfigManager() {
    }

    public static ConfigManager getInstance() {
        return configManager;
    }

    /**
     * 获取配置
     *
     * @return
     */
    @Override
    public Map<String, String> getConfig() {
        if (config == null) {
            refreshConfig();
        }
        return config;
    }

    /**
     * 刷新配置
     */
    @Override
    public void refreshConfig() {
        try {
            List<ConfigDTO> configDTOs = configDao.list();
            if (config == null) {
                config = new HashMap<>(0);
            } else {
                config.clear();
            }
            configDTOs.forEach(configDTO -> {
                config.put(configDTO.getConfigKey(), configDTO.getConfigValue());
            });
        } catch (SearchException e) {
            LOG.error(e.getMessage(), e);
        }
    }

    public void setConfigDao(IConfigDao configDao) {
        this.configDao = configDao;
    }

    private static class ConfigManagerBuilder {
        public static final ConfigManager configManager = new ConfigManager();
    }

}
