import { ConfigRequire } from '../models/ConfigRequire'
import { ConfigLoader } from './ConfigLoader'
import * as fs from 'fs'
import * as util from 'util'

export class ConfigLoaderLocal extends ConfigLoader {

    /**
     * 加载配置
     * @param configData 配置内容
     */
    async load(configData: Map<string, any>, configRequires: Array<ConfigRequire>){
        if (!configRequires || configRequires.length == 0) {
            return
        }
        for (const configRequire of configRequires) {
            await this.pullConfigFile(configData, configRequire)
        }
    }


    private async pullConfigFile(configData: Map<string, any>, configRequire: ConfigRequire) {
        const filePath = this.assembleFilePath(configRequire)
        const fs_exists = util.promisify(fs.exists)
        const fs_readFile = util.promisify(fs.readFile)
        if (!(await fs_exists(filePath))) { //判断文件是否存在
            return;
        }
        const config = (await fs_readFile(filePath)).toString();
        if (config) {
            const configObj = JSON.parse(config.toString());
            const keys = Object.keys(configObj)
            keys.forEach(key => {
                configData.set(key, configObj[key])
            })
        }
    }

}