import { execa } from 'execa';
import path from 'node:path';
import __dirname from './__dirname.js';
const ongoingTasks = {};
const waitingDeleteFiles = {};
const execPath = path.join(__dirname(import.meta.url), './nodeExec.js');
export function start(name, command, options, log) {
    const monitor = execa(process.execPath, [execPath, command, JSON.stringify(options)], {
        stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
        env: {
            USED_BY_APP: options.usedBy || 'browser',
        },
    });
    const handleLog = (_log) => {
        var _a, _b;
        (_a = monitor.stdout) === null || _a === void 0 ? void 0 : _a.on('data', (e) => {
            const str = e.toString();
            if (str) {
                _log(str.split('\n').filter(Boolean).join('\n'), 'succeed');
            }
        });
        (_b = monitor.stderr) === null || _b === void 0 ? void 0 : _b.on('data', (e) => {
            const str = e.toString();
            _log(str, 'failed');
        });
    };
    if (log) {
        handleLog(log);
    }
    monitor.on('message', (r) => {
        const files = r;
        if (files.length) {
            waitingDeleteFiles[name] = r;
        }
    });
    const myMonitor = {
        handleLog,
        original: monitor,
        kill: () => monitor.kill('SIGKILL'),
    };
    ongoingTasks[name] = myMonitor;
    return myMonitor;
}
export function has(name) {
    return !!ongoingTasks[name];
}
export function cancel(name) {
    const monitor = ongoingTasks[name];
    if (!monitor) {
        throw new Error(`任务 ${name} 没有在进行中`);
    }
    if (monitor.kill()) {
        ongoingTasks[name] = null;
        return true;
    }
    return false;
}
export function get(name) {
    return ongoingTasks[name];
}
export function getFiles(name) {
    return waitingDeleteFiles[name];
}
export function clearFiles(name) {
    waitingDeleteFiles[name] = null;
    return true;
}
