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

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) console.log("xml中无配置加载");
		else {
            //必要配置
            let integralConfig = ["port", "host"];
            
            checkConfig(integralConfig, configInfo.config);

			let {port, host} = configInfo.config;

			systemConfig.port = parseInt(port[0]);
            systemConfig.host = host[0];
		}

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

function checkConfig(config, configData) {
    config.forEach(item => {
        if (typeof item == "object") {
            for (let key in item) {
                if (!configData[key] || !configData[key][0]) {
                    // throw new SysError(SYSTEMERRORENUM.初始化配置失败, `serverConfig.xml中 缺少 ${key}`);
                    console.log("初始化配置失败");
                }
                item[key].forEach( subItem => {
                    if (!configData[key][0][subItem] || !configData[key][0][subItem][0]) {
                        // throw new SysError(SYSTEMERRORENUM.初始化配置失败, `serverConfig.xml中 ${key}缺少 ${subItem}`);
                        console.log("初始化配置失败");
                    }
                });

            }
        } else {
            if (!configData[item] || !configData[item][0]) {
                // throw new SysError(SYSTEMERRORENUM.初始化配置失败, `serverConfig.xml中 缺少 ${item}`);
                console.log("初始化配置失败");
            }
        }
    });
}
