"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.jestResultsToIdMap = exports.readRunResultsDirToMap = exports.intersectJestAndScreenplay = exports.prepareRunConclusion = exports.readRunConclusion = exports.writeRunConclusion = exports.writeRunsHistory = exports.updateRunsHistory = exports.readRunsHistory = void 0;
const utils_1 = require("../../utils");
const fs_extra_1 = __importDefault(require("fs-extra"));
const p_map_1 = __importDefault(require("p-map"));
const p_filter_1 = __importDefault(require("p-filter"));
const path_1 = __importDefault(require("path"));
const consts_1 = require("../../consts");
async function readRunsHistory(screenplayDirPath) {
    try {
        return JSON.parse(await fs_extra_1.default.readFile(path_1.default.resolve(screenplayDirPath, consts_1.HISTORY_FILE_NAME), 'utf8'));
    }
    catch (e) {
        return [];
    }
}
exports.readRunsHistory = readRunsHistory;
function updateRunsHistory(history, conclusion, historyToKeep) {
    const runIdAlreadyInUse = history.findIndex((h) => h.runId === conclusion.runId);
    if (runIdAlreadyInUse > -1) {
        history.splice(runIdAlreadyInUse, 1);
    }
    history.unshift({
        runId: conclusion.runId,
        timestamp: conclusion.timestamp,
    });
    history.splice(historyToKeep);
}
exports.updateRunsHistory = updateRunsHistory;
async function writeRunsHistory(screenplayDirPath, history) {
    return fs_extra_1.default.writeFile(path_1.default.resolve(screenplayDirPath, consts_1.HISTORY_FILE_NAME), JSON.stringify(history, null, 2));
}
exports.writeRunsHistory = writeRunsHistory;
async function writeRunConclusion(screenplayDirPath, runId, conclusion) {
    return fs_extra_1.default.writeFile(path_1.default.resolve(screenplayDirPath, consts_1.SCREENPLAY_RUNS_DIR_NAME, runId, consts_1.SCREENPLAY_RUN_CONCLUSION_FILE_NAME), JSON.stringify(conclusion, null, 2));
}
exports.writeRunConclusion = writeRunConclusion;
async function readRunConclusion(screenplayDirPath, runId) {
    return JSON.parse(await fs_extra_1.default.readFile(path_1.default.resolve(screenplayDirPath, consts_1.SCREENPLAY_RUNS_DIR_NAME, runId, consts_1.SCREENPLAY_RUN_CONCLUSION_FILE_NAME), 'utf8'));
}
exports.readRunConclusion = readRunConclusion;
function prepareRunConclusion(runId, timestamp, data) {
    const conclusion = {
        runId,
        timestamp,
        tests: [...data].map(([id, entry]) => ({
            id,
            name: entry.jest.testResult.title,
            fullName: entry.jest.testResult.fullName,
            success: entry.jest.testResult.status === 'passed',
        })),
    };
    return conclusion;
}
exports.prepareRunConclusion = prepareRunConclusion;
function intersectJestAndScreenplay(screenplaySide, jestSide) {
    const finalMap = new Map();
    for (const [testId, screenplayEntry] of screenplaySide) {
        const jestEntry = jestSide.get(testId);
        if (screenplayEntry && jestEntry && (jestEntry.testResult.status === 'passed' || jestEntry.testResult.status === 'failed')) {
            finalMap.set(testId, {
                jest: jestEntry,
                screenplay: screenplayEntry,
            });
        }
    }
    return finalMap;
}
exports.intersectJestAndScreenplay = intersectJestAndScreenplay;
async function readRunResultsDirToMap(inputDir) {
    if (!await fs_extra_1.default.pathExists(inputDir)) {
        return new Map();
    }
    const resultsDirsList = await p_filter_1.default(await fs_extra_1.default.readdir(inputDir), async (maybeDirPath) => {
        if (!(await fs_extra_1.default.stat(path_1.default.resolve(inputDir, maybeDirPath))).isDirectory()) {
            return false;
        }
        return fs_extra_1.default.pathExists(path_1.default.resolve(inputDir, maybeDirPath, consts_1.SCREENPLAY_RESULTS_FILE_NAME));
    }, { concurrency: 4 });
    const resultsList = await Promise.all(await p_map_1.default(resultsDirsList, async (singleResultDirName) => {
        const singleResultDir = path_1.default.resolve(inputDir, singleResultDirName);
        const singleResultFile = path_1.default.resolve(singleResultDir, consts_1.SCREENPLAY_RESULTS_FILE_NAME);
        const testData = JSON.parse(await fs_extra_1.default.readFile(singleResultFile, 'utf8'));
        const id = singleResultDirName;
        return {
            singleResultDir,
            id,
            testData,
        };
    }, { concurrency: 4 }));
    return new Map(resultsList.map(e => ([e.id, e])));
}
exports.readRunResultsDirToMap = readRunResultsDirToMap;
function jestResultsToIdMap(jestSuiteResults, projectRoot) {
    const flattedSuites = utils_1.arrayFlat(jestSuiteResults.map((s) => s.testResults.map((r) => ({
        testResult: r,
        suiteFilePath: path_1.default.relative(projectRoot, s.testFilePath),
        id: utils_1.testUniqueIdentifierFromStartParams({ projectRoot, fullSuitePath: s.testFilePath, fullName: r.fullName }),
    }))));
    return new Map(flattedSuites.map(e => ([e.id, e])));
}
exports.jestResultsToIdMap = jestResultsToIdMap;
