import { exec } from 'child_process';
import process from 'process';
import { formatMac, isVirtualMac, logDebug } from './utils';
function execPromisfy(cmd, options = {}, trimEmptyLine = false) {
    return new Promise(resolve => {
        exec(cmd, { windowsHide: true, ...options }, (error, stdout, stderr) => {
            if (error)
                console.error('exec error:', `cmd: ${cmd}\n`, error.message || error);
            stdout = stdout.replace(/\r+\n/g, '\n').trim();
            if (trimEmptyLine)
                stdout = stdout.replace(/\n{2,}/g, '\n');
            resolve({ error, stdout, stderr });
        });
    });
}
export async function getNetworkIFacesInfoByWmic() {
    const config = {};
    let stdout = '';
    if (process.platform === 'win32') {
        const keyMap = { MACAddress: 'mac', Description: 'desc' };
        const cmd = `wmic nic get MACAddress,Description /format:list`;
        const info = await execPromisfy(cmd);
        const lines = info.stdout.split('\n').filter(d => d.includes('='));
        stdout = info.stdout;
        if (lines[0]) {
            let item = {};
            const setToConfig = () => {
                if (item.mac) {
                    item.mac = formatMac(item.mac);
                    if (!config[item.mac] || !isVirtualMac('', item.desc))
                        config[item.mac] = item;
                }
                item = {};
            };
            for (const line of lines) {
                let [key, value] = line.split('=').map(d => d.trim());
                key = keyMap[key] || key.toLowerCase();
                if (item[key])
                    setToConfig();
                item[key] = value;
            }
            setToConfig();
        }
        if (stdout)
            logDebug(`[getNetworkIFacesInfoByWmic]`, stdout, config);
    }
    return { stdout, config };
}
