import { Singleton, Container, Scope, Inject } from "typescript-ioc";
import { HttpClient } from './HttpClient'
import { logger, OpResult } from 'mslib'
/**
 * 配置中心客户端
 * @date 2021-05-31 11:26:17
 * @author 吴锋霖
 */
@Singleton
class SimpleConfigClient {

    @Inject
    private httpClient: HttpClient

    /**
     * 从配置中心加载配置内容
     * @param parameters
     */
    async getConfig(env: string, envKey: string, configCode: string, version: string): Promise<OpResult<any>> {
        const configServerUrl = process.env['KT_CONFIG_SERVER_URL'] + '/getConfigFile/json'
        const params = {} as any
        params["meEnv"] = env;
        params["meEnvKey"] = envKey;
        params["configCode"] = configCode;
        params["version"] = version

        logger.info('准备开始从配置中心拉取配置------:%s-------:%j', configServerUrl, params)
        const response = await this.httpClient.get(configServerUrl, params)
     
        if (response && response.status === 200) {
            const opResult = response.data
            if (opResult.code !== 2000) {
                return opResult
            }
            logger.debug('加载配置中心配置成功--->ENV:%s ,configCode:%s,version：%s', env, configCode, version)
            return opResult
        } else {
            logger.error('加载配置中心配置失败--->ENV:%s ,configCode:%s,version：%s, response :%j', env, configCode, version, response)
            return OpResult.error('加载配置中心配置失败 :' + response.status)
        }
    }

}

export { SimpleConfigClient }