import {EnvVariables, logger} from "mslib"

const path = require('path')
const fs = require("fs")

export class NodeHttpPortUtil {

    static getHttpPort() {
        const commonIniPort = this.readCommonIniPort()
        if (commonIniPort) {
            logger.info('从common.ini 中解析得到端口号:' + commonIniPort)
            return commonIniPort
        }
        let httpPort = 31000; //HTTP 端口号
        if (EnvVariables.getNodeHttpPort() && EnvVariables.getNodeHttpPort().length > 0) {
            httpPort = parseInt(EnvVariables.getNodeHttpPort())
        }
        return httpPort;
    }

    /**
     * 读取common.ini 私有化部署配置文件端口号
     * @returns
     */
    static readCommonIniPort() {
        try {
            const filePath = path.join(__dirname, "../../common.ini")
            const data = fs.readFileSync(filePath, "utf-8")
            const lines = data.split(/\r?\n/);
            for (let line of lines) {
                if (line.startsWith('port=')) {
                    return parseInt(line.replace('port=', '').trim())
                }
            }
        } catch (e) {
            if (e.code === 'ENOENT') {
                return undefined
            }
            logger.error('解析common.ini文件异常',e)
        }
        return undefined
    }
}