"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateJunitReport = exports.persist = void 0;
const testim_services_api_1 = require("./testim-services-api");
const testim_credentials_manager_1 = require("./testim-credentials-manager");
const path_1 = require("path");
const utils_1 = require("./utils");
const fs_extra_1 = __importDefault(require("fs-extra"));
const ora_1 = __importDefault(require("ora"));
const untildify_1 = __importDefault(require("untildify"));
async function persist(runId, { projectRoot, resultLabel, project, token, jUnitReportPath, }) {
    if (!runId) {
        console.log('Please pass a valid runId');
        return;
    }
    const credentials = project && token ? { projectId: project, ciToken: token } : await testim_credentials_manager_1.getTestimCredentials();
    if (!jUnitReportPath && process.env.TESTIM_PROJECT_JUNIT_PATH) {
        jUnitReportPath = untildify_1.default(process.env.TESTIM_PROJECT_JUNIT_PATH);
    }
    if (!credentials.ciToken || !credentials.projectId) {
        console.log('No Root Cause Credentials found, please make sure the TESTIM_PROJECT_ID' +
            ' and TESTIM_PROJECT_TOKEN environment variables are defined.');
        return;
    }
    const api = new testim_services_api_1.TestimApi(process.env.SERVICES_URL);
    await api.authenticate(credentials.projectId, credentials.ciToken);
    const dir = utils_1.constructResultDir(projectRoot || process.cwd());
    const path = path_1.resolve(dir, 'runs', runId);
    if (!(await fs_extra_1.default.pathExists(path))) {
        console.log('Run does not exist, looked at', path);
        return;
    }
    const spinner = ora_1.default(`Up´ tests for suite run ${runId}`).start();
    try {
        if (!Array.isArray(resultLabel)) {
            resultLabel = [];
        }
        resultLabel.push('RootCause');
        const { testimFormat } = await api.executionsApi.createExecution(path, {
            projectId: credentials.projectId,
            resultLabels: resultLabel,
            companyId: '',
        }, (progress) => {
            const text = `${(progress * 100).toFixed(2)}%`;
            spinner.text = `Uploading tests for suite run ${runId} (${text})`;
        });
        spinner.succeed('Execution Created Successfully');
        try {
            if (jUnitReportPath) {
                await saveJunitReport({
                    jUnitReportPath,
                    testimExecution: testimFormat,
                    projectId: credentials.projectId,
                });
                console.log('Report file saved at ', jUnitReportPath);
            }
        }
        catch (e) {
            console.error('Error generating jUnit Report', e);
        }
        spinner.succeed(`Watch your tests in https://app.testim.io/#/project/${credentials.projectId}/runs/suites/${testimFormat.runId}`);
    }
    catch (e) {
        spinner.fail(`Error Creating Execution: ${e && e.message}`);
        console.error(e);
    }
}
exports.persist = persist;
async function saveJunitReport({ jUnitReportPath, testimExecution, projectId, }) {
    const report = generateJunitReport({ testimExecution, projectId });
    await fs_extra_1.default.writeFile(jUnitReportPath, report);
}
function generateJunitReport({ testimExecution, projectId, }) {
    const actualTests = Object.values(testimExecution.execution).filter((test) => !test.isTestsContainer);
    const dateValue = new Date(testimExecution.startTime).toUTCString();
    const files = Object.values(testimExecution.execution).filter((test) => test.isTestsContainer);
    const baseUrl = `https://app.testim.io/#/project/${projectId}/branch/master/root-cause/run/${testimExecution.runId}`;
    const attr = (str) => `"${str.replace(/"/g, '&quot').replace(/&/g, '&amp').replace(/</, '&lt;')}"`;
    const report = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><testsuites disabled='0'>${files
        .map((file) => {
        const tests = actualTests.filter((x) => x.parentResultId === file.resultId);
        const failed = tests.filter((x) => !x.success);
        return `\t<testsuite name=${attr(file.name)} tests="${tests.length}" failure="${failed.length}" failures="${failed.length}" timestamp="${dateValue}">
                 ${tests
            .map((test) => `<testcase name=${attr(test.name)} classname="rootcause.test"><system-out>${baseUrl}/test/${test.testId}</system-out></testcase>`)
            .join('\n\t\t\t\t')}
             </testsuite>`;
    })
        .join('\n\t\t\t')}
         <system-out>Suite Run URL: ${baseUrl}</system-out>
    </testsuites>`;
    return report;
}
exports.generateJunitReport = generateJunitReport;
