const path = require('path');
import * as fs from "fs";
import { BizError } from "../util/bizError";
import { analysisXml } from "../util/myXML";
import { ServerConfig } from "../config/systemClass";
const os = require('os');

export let systemConfig =  new ServerConfig;

const ConfigName = "serverConfig.xml";
export async function initConfig() {
    try {
        let buff = fs.readFileSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), ConfigName));
        let configStr = buff.toString();
        let configInfo:any = await analysisXml(configStr);
		if (!configInfo || !configInfo.config) throw new BizError('xml中无配置');
		else {
            
            let {port, mongodb, getOpenIdUrl, appId, sms, baidumap } = configInfo.config;
            systemConfig.port = parseInt(port[0]);
            
            const MongoPath = mongodb[0].path[0];
            const MongoPort = mongodb[0].port[0];
            const MongoW = mongodb[0].w[0];
            const MongoDataBase = mongodb[0].dataBase[0];
            const MongoWtimeoutMS = mongodb[0].wtimeoutMS[0];
            systemConfig.mongodbStr = analysisMongoConnectStr( MongoPath, MongoPort, MongoDataBase, MongoW, MongoWtimeoutMS);

		}
        
        console.log("config init success");

    } catch(err) {
        console.log('ERROR => 服务器配置解析错误 请检查根目录下 serverConfig.xml 文件是否正确');
        console.log(err);
        throw new BizError("服务器配置解析错误 请检查根目录下 serverConfig.xml 文件是否正确");
    }
}

function analysisMongoConnectStr(path, port, dataBase, w, timeOutMs) {
    return `mongodb://${path}:${port}/${dataBase}?w=${w}&wtimeoutMS=${timeOutMs}`
}