"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;
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeTunnelManagerServerProcess = exports.makeTunnelManagerServer = void 0;
const net_1 = require("net");
const logger_1 = require("@applitools/logger");
const socket_1 = require("@applitools/socket");
const manager_1 = require("./manager");
const child_process_1 = require("child_process");
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const LOG_DIRNAME = (_a = process.env.APPLITOOLS_LOG_DIR) !== null && _a !== void 0 ? _a : path.resolve(os.tmpdir(), `applitools-tunnel-logs`);
async function makeTunnelManagerServer({ settings, path, idleTimeout = 600000, // 10min
 }) {
    var _a, _b;
    try {
        const server = await new Promise((resolve, reject) => {
            const server = (0, net_1.createServer)().listen({ path });
            server.on('error', error => reject(error));
            server.on('listening', () => resolve(server));
        });
        const logger = (0, logger_1.makeLogger)({
            handler: { type: 'rolling file', name: 'ec-tunnel-manager', dirname: LOG_DIRNAME },
            level: 'info',
            format: {
                label: 'ec-tunnel-manager',
                colors: false,
            },
        });
        logger.log('Server is started');
        const manager = await (0, manager_1.makeTunnelManager)({ settings, logger });
        (_a = process.send) === null || _a === void 0 ? void 0 : _a.call(process, { name: 'started', payload: { path } });
        let idle;
        let serverClosed = false;
        if (idleTimeout)
            idle = setTimeout(close, idleTimeout);
        server.on('close', () => {
            if (idle)
                clearTimeout(idle);
            serverClosed = true;
        });
        const sockets = new Set();
        server.on('connection', client => {
            const store = [];
            if (idle)
                idle = clearTimeout(idle);
            const socket = (0, socket_1.makeSocket)(client, { transport: 'ipc', logger });
            sockets.add(socket);
            socket.on('close', async () => {
                logger.log('Connection is closed, remaining tunnels are going to be released', store);
                await Promise.all(store.map(manager.release)).catch(logger.error);
                if (sockets.size === 0 && !serverClosed)
                    idle = setTimeout(close, idleTimeout);
            });
            socket.command('Tunnel.acquire', async (credentials) => {
                const tunnels = await manager.acquire(credentials);
                store.push(tunnels);
                return tunnels;
            });
            socket.command('Tunnel.release', async (tunnels) => {
                await manager.release(tunnels);
                const storeIndex = store.findIndex(storedTunnels => tunnels.every((tunnel, index) => tunnel.tunnelId === storedTunnels[index].tunnelId));
                tunnels.splice(storeIndex, 1);
            });
        });
        return { close };
        async function close() {
            logger.log('Server is going to be closed');
            server.close();
            await manager.close();
            process.kill(0);
        }
    }
    catch (error) {
        (_b = process.send) === null || _b === void 0 ? void 0 : _b.call(process, { name: 'error', payload: { error: { message: error.message, code: error.code, stack: error.stack } } });
        throw error;
    }
}
exports.makeTunnelManagerServer = makeTunnelManagerServer;
async function makeTunnelManagerServerProcess(options) {
    return new Promise((resolve, reject) => {
        const server = (0, child_process_1.fork)(path.resolve(__dirname, '../../dist/cli/cli.js'), [`tunnel-manager`, `--config=${JSON.stringify(options)}`], {
            stdio: ['ignore', 'ignore', 'inherit', 'ipc'],
            detached: true,
        });
        const timeout = setTimeout(() => {
            reject(new Error(`Server didn't respond for 10s after being started`));
            server.kill();
        }, 10000);
        server.on('error', reject);
        server.once('message', (message) => {
            const { name, payload } = message;
            server.channel.unref();
            if (name === 'started') {
                resolve({ close: async () => void server.kill() });
                clearTimeout(timeout);
            }
            else if (name === 'error') {
                const error = new Error(payload.error.message);
                error.code = payload.error.code;
                error.stack = payload.error.stack;
                reject(error);
                clearTimeout(timeout);
            }
        });
        server.unref();
    });
}
exports.makeTunnelManagerServerProcess = makeTunnelManagerServerProcess;
