"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.serveMhtml = void 0;
const debug_1 = __importDefault(require("debug"));
const fast_mhtml_1 = require("fast-mhtml");
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const logger = debug_1.default('root-cause:debug:serve-mhtml');
function sendFile(res, file) {
    logger('serve-mhtml: sending file %s', file.filename);
    res.setHeader('Content-Type', file.type);
    res.send(file.content);
    res.end();
}
function failWith(res, status, error) {
    logger('serve-mhtml: %s', error);
    res.status(status);
    res.send(error);
    res.end();
}
function serveMhtml(testPath) {
    const fileCache = new Map();
    async function processMhtml(file) {
        fileCache.clear();
        const data = await fs_extra_1.default.readFile(path_1.default.resolve(testPath, file));
        const splitFiles = new fast_mhtml_1.Parser({}).parse(data).rewrite().spit();
        for (const result of splitFiles) {
            fileCache.set(result.filename.replace(/#.*/, ''), result);
        }
        return splitFiles[0];
    }
    return function serveMhtmlMiddleware({ params: { file } }, res) {
        (async () => {
            if (file.endsWith('mhtml')) {
                const indexFromHtml = await processMhtml(file);
                return sendFile(res, indexFromHtml);
            }
            const result = fileCache.get(file);
            if (!result) {
                return failWith(res, 404, `Missing ${file}, should be one of: ${JSON.stringify(fileCache.keys())}`);
            }
            sendFile(res, result);
        })().catch((error) => {
            return failWith(res, 500, `Error: ${error}<br />${error.stack.replace(/\n/, '<br />')}`);
        });
    };
}
exports.serveMhtml = serveMhtml;
