const path = require('path');
import * as fs from "fs";
import { BizError } from "../util/bizError";
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) throw new BizError('xml中无配置');
        
        let { port, sign, img, mysqldb, mqttsrv } = configInfo.config;
        
        // 基本配置
        systemConfig.port = parseInt(port[0]);
        systemConfig.sign = sign[0];
        systemConfig.img = img[0];
        
        // MySQL配置
        if (mysqldb) {
            let dbConfigInfo = mysqldb[0];
            systemConfig.mysqldb = { host: '', port: 0, user: '', pwd: '', dataBase: '' };
            
            if (dbConfigInfo.mysqlHost && dbConfigInfo.mysqlPort && dbConfigInfo.mysqlUser && dbConfigInfo.dataBase) {
                systemConfig.mysqldb.host = dbConfigInfo.mysqlHost[0];
                systemConfig.mysqldb.port = parseInt(dbConfigInfo.mysqlPort[0]);
                systemConfig.mysqldb.user = dbConfigInfo.mysqlUser[0];
                systemConfig.mysqldb.pwd = dbConfigInfo.mysqlPwd[0] || "";
                systemConfig.mysqldb.dataBase = dbConfigInfo.dataBase[0];
            }
        }

        // mqtt
        if (mqttsrv) {
            let configInfo = mqttsrv[0];
            systemConfig.mqttsrv = { host: '', port: 0, topic_env: '', topic_crowd: '', username: '', password: '' };
            
            if (configInfo.mqttHost && configInfo.mqttPort && (configInfo.mqttTopic1 || configInfo.mqttTopic2)) {
                systemConfig.mqttsrv.host = configInfo.mqttHost[0];
                systemConfig.mqttsrv.port = parseInt(configInfo.mqttPort[0]);
                systemConfig.mqttsrv.topic_env = configInfo.mqttTopic1[0];
                systemConfig.mqttsrv.topic_crowd = configInfo.mqttTopic2[0];
                systemConfig.mqttsrv.username = configInfo.username[0];
                systemConfig.mqttsrv.password = configInfo.password[0];
            }
        }

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



