import HttpUtils from './HttpUtils';
import {Container} from 'typescript-ioc';
import {ConfigClient, logger} from 'mslib';


/**
 * 配置文件加载器
 */
class ConfigLoader {

    /**
     * 加载配置文件到环境变量中
     */
    static async load(): Promise<any>  {
        const MS_CONFIG_URL = process.env.MS_CONFIG_URL
        if (MS_CONFIG_URL && MS_CONFIG_URL.toString().length > 0) {
            return await this.loadByUrl(MS_CONFIG_URL);
        } else {
            return await this.loadByConfigCenter()
        }
    }

    /**
     * 从配置中心加载配置
     * @param callback
     */
    static async loadByConfigCenter(): Promise<any> {
        const configClient = Container.get(ConfigClient);
        const configRequires = [];
        //加载中台默认配置
        const defaultConfigs = (process.env.KT_DEFAULT_CONFIG_REQUIRES || '').split(',')
        if (defaultConfigs && defaultConfigs.length > 0) {
            for (let defaultConfig of defaultConfigs) {
                const config = defaultConfig.split(":");
                if (config.length === 2) {
                    configRequires.push({ version: config[1], configCode: config[0] })
                }
            }
        }
        //下面這個configRequire是个占位符，不可删除
        /*configRequire*/
        await configClient.initClient(configRequires);
        const allConfig = configClient.getAllConfig();
        return allConfig
    }

    /**
     * 从外部配置URL中加载配置内容
     * @param MS_CONFIG_URL
     * @param callback
     */
    static async loadByUrl(MS_CONFIG_URL: string): Promise<any> {
        try {
            const config = (await HttpUtils.get(MS_CONFIG_URL)).data
            if (config) {
                for (let attr in config) {
                    process.env[attr] = config[attr]
                }
                return config
            } else {
                throw new Error('加载配置文件异常，返回空数据')
            }
        } catch (e) {
            logger.error("加载配置异常----", e)
            throw e
        }

    }

}

export {ConfigLoader}