package cn.anicert.secure.access.config;

import cn.anicert.secure.access.config.bean.AccessConfig;
import cn.anicert.secure.access.enums.Configs;
import cn.anicert.secure.access.exceptions.SecureAccessConfigException;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import cn.hutool.setting.Setting;
import cn.hutool.setting.SettingUtil;

import java.util.Arrays;

public class ConfigReader {
    private final static String CONFIG_FILE_NAME = "secure-access.setting";
    private static Setting setting;

    public static AccessConfig readConfig(String... filePath) {
        if (filePath == null || filePath.length == 0) {
            setting = SettingUtil.getFirstFound(CONFIG_FILE_NAME);
        } else {
            setting = SettingUtil.getFirstFound(filePath);
        }
        StaticLog.info("[安全接入平台]当前配置文件路径为:{}", setting.getSettingPath());
        StaticLog.info("[安全接入平台]开始读取配置文件…………");
        AccessConfig accessConfig = new AccessConfig();
        Arrays.stream(Configs.values()).forEach(config -> {
            if (config.isNecessary()) {
                if (setting.containsKey(config.getKey())) {
                    String value = setting.getStr(config.getKey());
                    if (StrUtil.isBlank(value)) {
                        StaticLog.error("[安全接入平台]{}未配置", config.getName());
                        throwConfigException();
                    }
                } else {
                    StaticLog.error("[安全接入平台]{}未配置", config.getName());
                    throwConfigException();
                }
            }
        });
        setting.autoLoad(true);
        setting.toBean(accessConfig);
        StaticLog.info("[安全接入平台]读取配置文件结束");
        return accessConfig;
    }

    public static AccessConfig writeConfig(String key, String value) {
        setting.set(key, value);
        setting.store();
        AccessConfig accessConfig = new AccessConfig();
        return setting.toBean(accessConfig);
    }

    private static void throwConfigException() {
        throw new SecureAccessConfigException("[安全接入平台]读取配置文件失败");
    }

}
