"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.launchImpl = exports.launch = void 0;
const attach_1 = require("./attach");
const consts_1 = require("./consts");
const updateHistoryFromRootCauseResultsOnly_1 = require("./updateHistoryFromRootCauseResultsOnly");
const open_1 = __importDefault(require("open"));
const chalk_1 = __importDefault(require("chalk"));
const server_1 = require("./server");
const envVarsWrapper_1 = require("./envVarsWrapper");
const utils_1 = require("./utils");
const persist_1 = require("./persist");
const userSettings_1 = require("./userSettings/userSettings");
function launch(options, userTestFunction) {
    return launchImpl(options, userTestFunction);
}
exports.launch = launch;
async function launchImpl(options, userTestFunction, dateConstructor = Date) {
    var _a, _b;
    let browser;
    const userSettings = await userSettings_1.loadSettings();
    if (options.automationLibrary === 'playwright') {
        const playwrightBrowserOptions = options.browserOptions
            ? options.browserOptions
            : { browser: 'chromium' };
        if ('headless' in options && !('headless' in playwrightBrowserOptions)) {
            playwrightBrowserOptions.headless = options.headless;
        }
        browser = await launchPlaywrightByOptions(playwrightBrowserOptions);
    }
    else {
        const puppeteerOpts = {};
        if ((_a = options.browserOptions) === null || _a === void 0 ? void 0 : _a.browserArgs) {
            puppeteerOpts.args = (_b = options.browserOptions) === null || _b === void 0 ? void 0 : _b.browserArgs;
        }
        if ('headless' in options) {
            puppeteerOpts.headless = options.headless;
        }
        if (options.browserOptions && 'headless' in options.browserOptions) {
            puppeteerOpts.headless = options.browserOptions.headless;
        }
        browser = await require('puppeteer').launch(puppeteerOpts);
    }
    const realPage = await browser.newPage();
    const callSite = utils_1.getSelfCallSiteFromStacktrace();
    const fullSuitePath = (callSite === null || callSite === void 0 ? void 0 : callSite.getFileName()) || 'no_suite_available';
    const startTestParams = {
        runId: options._runId ? options._runId : consts_1.FALLBACK_RUN_ID,
        fullName: `${dateConstructor.now()}-${options.testName}`,
        description: options.testName,
        projectRoot: process.cwd(),
        fullSuitePath,
    };
    const { page, endTest } = await attach_1.attach({ page: realPage, startTestParams, activeFeatures: userSettings.features }, dateConstructor);
    try {
        await userTestFunction(page);
        await endTest({
            success: true,
        });
    }
    catch (error) {
        await endTest({
            success: false,
            error,
        });
        throw error;
    }
    finally {
        await updateHistoryFromRootCauseResultsOnly_1.updateHistoryFromRootCauseResultsOnly(startTestParams.runId, startTestParams.projectRoot, dateConstructor);
        await browser.close();
        if (!options.noServer) {
            const url = await server_1.openServer(envVarsWrapper_1.TEST_API_PORT, utils_1.testResultDirFromStartParams(startTestParams));
            console.log(chalk_1.default.blue(`Root Cause viewer: ${url}`));
            open_1.default(url);
            console.log('Press any key to exit');
            if (process.stdin.isTTY) {
                process.stdin.setRawMode(true);
            }
            process.stdin.resume();
            process.stdin.once('data', async () => {
                await persistIfNeeded(startTestParams);
                server_1.closeServer();
                process.exit(0);
            });
        }
        else {
            await persistIfNeeded(startTestParams);
        }
    }
}
exports.launchImpl = launchImpl;
async function persistIfNeeded(startTestParams) {
    var _a;
    if (process.env.TESTIM_PERSIST_RESULTS_TO_CLOUD) {
        await persist_1.persist(startTestParams.runId, {
            projectRoot: startTestParams.projectRoot,
            resultLabel: (_a = global.resultLabels) !== null && _a !== void 0 ? _a : null,
        });
    }
}
function launchPlaywrightByOptions(options) {
    const playwrightPlatform = require('playwright')[options.browser];
    return playwrightPlatform.launch({
        headless: options.headless,
        args: options.browserArgs,
    });
}
