"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createHtmlCollectionHook = void 0;
const fs_1 = require("fs");
const path_1 = require("path");
const utils_1 = require("../utils");
async function createHtmlCollectionHook(page) {
    let session = await utils_1.getChromeCDPSession(page);
    if (!session) {
        return async () => undefined;
    }
    return async function htmlCollectionHook({ testContext, stepResult, proxyContext }) {
        var _a;
        const pageToCaptureSnapshot = (_a = (await utils_1.getPageFromProxyContext(proxyContext))) !== null && _a !== void 0 ? _a : page;
        if (page !== pageToCaptureSnapshot) {
            try {
                session = await utils_1.getChromeCDPSession(pageToCaptureSnapshot);
            }
            catch (_b) {
            }
        }
        if (session === null) {
            return;
        }
        const { data: mhtmlContent } = await utils_1.sendCDPMessage(session, 'Page.captureSnapshot', {
            format: 'mhtml',
        });
        const mhtmlFile = `${stepResult.index}.document.mhtml`;
        const outputFilePath = path_1.join(testContext.testArtifactsFolder, mhtmlFile);
        await fs_1.promises.writeFile(outputFilePath, mhtmlContent);
        stepResult.mhtmlFile = mhtmlFile;
    };
}
exports.createHtmlCollectionHook = createHtmlCollectionHook;
