#! /usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const commander_1 = require("commander");
const open_1 = __importDefault(require("open"));
const server_1 = require("./server");
const prompts_1 = __importDefault(require("prompts"));
const utils_1 = require("./utils");
const runConclusionUtils_1 = require("./jest/reporter/runConclusionUtils");
const updateHistoryFromScreenplayResultsOnly_1 = require("./updateHistoryFromScreenplayResultsOnly");
commander_1.program.version(getVersion());
async function show(testId, { failed: showOnlyFailed = false } = {}) {
    const screenplayPath = utils_1.constructScreenplayResultDir(process.cwd());
    const history = await runConclusionUtils_1.readRunsHistory(screenplayPath);
    let conclusion = null;
    let runId = '';
    if (history.length === 0) {
        try {
            conclusion = await updateHistoryFromScreenplayResultsOnly_1.readHistoryFallback();
            runId = conclusion.runId;
        }
        catch (err) {
            if (history.length === 0) {
                console.log('No Screenplay runs found');
                console.log('Make sure you have the .screenplay directory in your working directory');
                return;
            }
        }
    }
    if (!conclusion) {
        const mostRecentHistory = history[0];
        runId = mostRecentHistory.runId;
        conclusion = await runConclusionUtils_1.readRunConclusion(screenplayPath, runId);
    }
    if (testId) {
        if (conclusion.tests.findIndex((t) => t.id === testId) === -1) {
            console.error(`Test with id ${testId} is missing`);
            process.exit(1);
            return;
        }
        const url = await server_1.openServer(9876, utils_1.constructTestResultDir(process.cwd(), runId, testId));
        open_1.default(url);
        console.log('Press any key to exit');
        if (process.stdin.isTTY) {
            process.stdin.setRawMode(true);
        }
        process.stdin.resume();
        process.stdin.on('data', process.exit.bind(process, 0));
    }
    else {
        const selectedTest = await prompts_1.default({
            type: 'select',
            name: 'test',
            message: 'Please select which test run to show',
            choices: conclusion.tests.filter(t => (showOnlyFailed ? !t.success : true)).map(p => ({ title: `${p.name} (${p.id})`, value: p.id })),
        });
        if (selectedTest.test !== undefined) {
            show(selectedTest.test);
        }
        else {
        }
    }
}
async function list({ simple = false, failed: showOnlyFailed = false } = {}) {
    const screenplayPath = utils_1.constructScreenplayResultDir(process.cwd());
    const history = await runConclusionUtils_1.readRunsHistory(screenplayPath);
    if (history.length === 0) {
        console.log('No Screenplay runs found');
        return;
    }
    const mostRecentHistory = history[0];
    const runId = mostRecentHistory.runId;
    const conclusion = await runConclusionUtils_1.readRunConclusion(screenplayPath, runId);
    if (simple) {
        for (const test of conclusion.tests) {
            console.log(test.id);
        }
        return;
    }
    console.log(`Run id: ${conclusion.runId}`);
    console.log(`Run time: ${new Date(conclusion.timestamp).toISOString()}`);
    const tableData = conclusion.tests
        .filter(t => (showOnlyFailed ? !t.success : true))
        .map(({ id, name, success, }) => ({
        id,
        name,
        success,
    }));
    console.table(tableData);
}
function version() {
    console.log(getVersion());
}
function getVersion() {
    const version = require('../package.json').version;
    return version;
}
function login() {
    const loginUrl = 'https://app.testim.io/#/signin?fromScreenplay=true';
    open_1.default(loginUrl);
}
commander_1.program
    .command('show [testId]')
    .description('shows test result ui')
    .option('-f, --failed', 'show only failed tests')
    .action(show);
commander_1.program
    .command('list')
    .alias('ls')
    .option('-s, --simple', 'print simple output, as unformatted as possible')
    .option('-f, --failed', 'show only failed tests')
    .description('list all screenplay runs')
    .action(list);
commander_1.program
    .option('-v')
    .description('output the version number')
    .action(version);
commander_1.program
    .command('login')
    .description('logs in to testim')
    .action(login);
commander_1.program.parse(process.argv);
