"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 updateHistoryFromScreenplayResultsOnly_1 = require("./updateHistoryFromScreenplayResultsOnly");
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");
function launch(options, userTestFunction) {
    return launchImpl(options, userTestFunction);
}
exports.launch = launch;
async function launchImpl(options, userTestFunction, dateConstructor = Date) {
    var _a, _b;
    let browser;
    if (options.automationLibrary === 'playwright') {
        browser = await launchPlaywrightByOptions(options.browserOptions || { browser: 'chromium' });
    }
    else {
        browser = await require('puppeteer').launch({
            args: (_a = options.browserOptions) === null || _a === void 0 ? void 0 : _a.browserArgs,
            headless: (_b = options.browserOptions) === null || _b === void 0 ? void 0 : _b.headless,
        });
    }
    const realPage = await browser.newPage();
    const startTestParams = {
        runId: consts_1.FALLBACK_RUN_ID,
        fullName: `${dateConstructor.now()}-${options.testName}`,
        description: options.testName,
        projectRoot: process.cwd(),
        fullSuitePath: 'no_suite_available',
    };
    const { page, endTest } = await attach_1.attach({ page: realPage, startTestParams }, dateConstructor);
    try {
        await userTestFunction(page);
        await endTest({
            success: true,
        });
    }
    catch (error) {
        await endTest({
            success: false,
            error,
        });
        throw error;
    }
    finally {
        await updateHistoryFromScreenplayResultsOnly_1.updateHistoryFromScreenplayResultsOnly(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(`Screenplay viewer: ${url}`));
            open_1.default(url);
        }
    }
}
exports.launchImpl = launchImpl;
function launchPlaywrightByOptions(options) {
    const playwrightPlatform = require('playwright')[options.browser];
    return playwrightPlatform.launch({
        headless: options.headless,
        args: options.browserArgs,
    });
}
