"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WIN32_PLATFORM = void 0;
exports.openUrlInDesktopApp = openUrlInDesktopApp;
exports.logSessionStarted = logSessionStarted;
const open_1 = __importDefault(require("open"));
const env_1 = require("../../env/env");
const timers_1 = require("timers");
const messaging_1 = require("../messaging/messaging");
const chalk_1 = __importDefault(require("chalk"));
const encodingUtil_1 = require("../../util/encodingUtil");
const http = __importStar(require("http"));
const MAX_URL_LENGTH = 1_500;
exports.WIN32_PLATFORM = 'win32';
async function createConfigServer(config) {
    const server = http.createServer((req, res) => {
        if (req.url === '/config') {
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify(config));
            server.close();
        }
        else {
            res.writeHead(404);
            res.end();
        }
    });
    return new Promise((resolve, reject) => {
        server.listen(0, () => {
            const port = server.address().port;
            const requestPromise = new Promise((resolveRequest) => {
                let timeout;
                if (process.platform !== exports.WIN32_PLATFORM) {
                    timeout = (0, timers_1.setTimeout)(() => {
                        resolveRequest();
                    }, 20_000);
                }
                server.on('close', () => {
                    if (timeout) {
                        global.clearTimeout(timeout);
                    }
                    resolveRequest();
                });
            });
            resolve({ port, server, requestPromise });
        });
        server.on('error', reject);
    });
}
async function openUrlInDesktopApp(url, trainingSessionOptions, waitProcessToExit = true) {
    let server;
    let childProcess;
    const params = (0, encodingUtil_1.encodeTestConfigAsParamsForParsedUrlProtocol)(trainingSessionOptions, encodingUtil_1.b64EncodeUnicodeInNode, false);
    let trainerUrl = `${env_1.ELECTRON_PROTOCOL}://${url}/${params}`;
    const urlLength = trainerUrl.length;
    if (urlLength > MAX_URL_LENGTH) {
        try {
            const serverResult = await createConfigServer({
                [encodingUtil_1.TEST_CONFIG_URL_PARAM_KEY]: (0, encodingUtil_1.b64EncodeUnicodeInNode)(JSON.stringify(trainingSessionOptions)),
            });
            server = serverResult.server;
            trainerUrl = `${env_1.ELECTRON_PROTOCOL}://${url}/configPort=${serverResult.port}`;
            if (process.platform === exports.WIN32_PLATFORM) {
                return trainerUrl;
            }
            childProcess = await (0, open_1.default)(trainerUrl);
            try {
                await serverResult.requestPromise;
            }
            catch (error) {
                messaging_1.mablEventEmitter.log(chalk_1.default.yellow('Failed to receive config request, falling back to URL-based approach'));
                childProcess = await (0, open_1.default)(`${env_1.ELECTRON_PROTOCOL}://${url}/${params}`);
            }
        }
        catch (error) {
            messaging_1.mablEventEmitter.log(chalk_1.default.yellow('Failed to create config server, falling back to URL-based approach'));
            childProcess = await (0, open_1.default)(`${env_1.ELECTRON_PROTOCOL}://${url}/${params}`);
        }
    }
    else if (process.platform === exports.WIN32_PLATFORM) {
        return trainerUrl;
    }
    else {
        childProcess = await (0, open_1.default)(`${env_1.ELECTRON_PROTOCOL}://${url}/${params}`);
    }
    let childProcessExited = false;
    const keepAliveUntilExited = () => {
        if (!childProcessExited) {
            (0, timers_1.setTimeout)(keepAliveUntilExited, 1000);
        }
    };
    keepAliveUntilExited();
    if (waitProcessToExit) {
        const exitCode = await new Promise((resolve) => {
            childProcess.on('error', () => {
                childProcessExited = true;
                server?.close();
                resolve(1);
            });
            childProcess.on('exit', function () {
                childProcessExited = true;
                server?.close();
                resolve(childProcess.exitCode);
            });
        });
        if (exitCode === 0) {
            logSessionStarted();
        }
        else {
            logInstallDesktopApp();
        }
    }
    return trainerUrl;
}
function logSessionStarted() {
    messaging_1.mablEventEmitter.log(chalk_1.default.yellowBright('Session started in the desktop app'));
}
function logInstallDesktopApp() {
    messaging_1.mablEventEmitter.log(chalk_1.default.red(`\nFailed to launch mabl desktop app!`, chalk_1.default.cyan(`\nPlease check your installation or download and install it from`), chalk_1.default.magenta('https://www.mabl.com/desktop-app')));
}
