"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NatsServer = void 0;
const cp = __importStar(require("child_process"));
// Mapping from Node's `process.arch` to Golang's `$GOARCH`
const ARCH_MAPPING = {
    ia32: '386',
    x64: 'amd64',
    arm: 'arm'
};
// Mapping between Node's `process.platform` to Golang's
const PLATFORM_MAPPING = {
    darwin: 'darwin',
    linux: 'linux',
    win32: 'windows',
    freebsd: 'freebsd'
};
function determineArch() {
    const arch = process.arch;
    const mapped = ARCH_MAPPING[arch];
    if (!mapped) {
        throw new Error('Unsupported architecture: ' + arch);
    }
    return mapped;
}
function determinePlatform() {
    const p = process.platform;
    const mapped = PLATFORM_MAPPING[p];
    if (!mapped) {
        throw new Error('Unsupported platform: ' + p);
    }
    return mapped;
}
class NatsServer {
    constructor(onUnexpectedStop, serverListenPort, clusterSeedUrls, clusterListenUrl, appName) {
        this.stopping = false;
        this.running = false;
        this.onUnexpectedStop = onUnexpectedStop;
        this.clusterSeedUrls = clusterSeedUrls;
        this.serverListenPort = serverListenPort;
        this.clusterListenUrl = clusterListenUrl;
        this.appName = appName;
    }
    start() {
        const arch = determineArch();
        const platform = determinePlatform();
        const ext = platform === 'windows' ? '.exe' : '';
        const filename = `nats-server-${platform}-${arch}${ext}`;
        const path = __dirname + '/../../binaries/';
        const fullname = path + filename;
        this.exeName = fullname;
        const args = [];
        args.push('--cluster_name');
        args.push('darlean');
        if (this.serverListenPort !== undefined) {
            args.push('--port');
            args.push(this.serverListenPort.toString());
        }
        if (this.clusterListenUrl) {
            args.push('--cluster');
            args.push(this.clusterListenUrl);
            if (this.clusterSeedUrls !== undefined && this.clusterSeedUrls.length > 0) {
                args.push('--routes');
                args.push(this.clusterSeedUrls.join(','));
            }
        }
        // console.log('STARTNG', fullname, args);
        const process = cp.execFile(fullname, args, (error, stdout, stderr) => {
            this.running = false;
            this.process = undefined;
            // console.log('NATS', error, stdout, stderr);
            if (!this.stopping) {
                this.onUnexpectedStop?.(stderr);
            }
        });
        this.running = true;
        this.process = process;
    }
    stop() {
        if (this.process && this.exeName && this.process.pid) {
            this.stopping = true;
            // TODO: Improve shuwdown on windows. Wndows does not know signals, it just has a hard kill, but
            // we want de graceful shutdown. We have filed an issue as Nats for this:
            // https://github.com/nats-io/nats-server/issues/3809
            // Note: ctrlc-windows package kills entire process tree including ourselves, so that
            // does not work.
            //const args = ['--signal', `stop=${this.process.pid}`]
            //console.log('----- STOPPING NATS', this.exeName, args);
            //cp.execFileSync(this.exeName, args);
            //this.process.stdin?.write('\u001a');
            //ctrlc.ctrlc(this.process.pid);
            this.process.kill();
            this.process = undefined;
        }
    }
    isRunning() {
        return this.running;
    }
}
exports.NatsServer = NatsServer;
