"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("@mablhq-internal/runtime/core/constants");
const constants_2 = require("../../constants");
const util_1 = require("../../commandUtil/util");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const cli_table3_1 = __importDefault(require("cli-table3"));
const moment = require("moment");
const loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
const js_yaml_1 = require("js-yaml");
exports.command = 'list';
exports.describe = 'List plans';
exports.builder = (yargs) => {
    yargs
        .option(constants_1.CommandArgWorkspaceId, {
        alias: constants_2.CommandArgAliases.WorkspaceId,
        describe: 'Workspace to list plans for',
        nargs: 1,
        type: 'string',
    })
        .option(constants_2.CommandArgOutput, {
        alias: constants_2.CommandArgAliases.OutputType,
        default: constants_1.OutputFormats.Table,
        describe: 'Specify result output format',
        nargs: 1,
        choices: [...constants_2.DefaultOutputFormatChoices, constants_1.OutputFormats.Table],
    })
        .option(constants_2.CommandArgLimitOutput, {
        alias: constants_2.CommandArgAliases.LimitOutput,
        describe: 'The number of plans to return',
        default: 10,
        nargs: 1,
        type: 'string',
    });
};
exports.handler = (0, cliUtil_1.failWrapper)(listPlans);
async function listPlans(parsed) {
    const limit = parsed.limit;
    const workspaceId = await (0, util_1.getWorkspaceId)(parsed);
    const output = parsed[constants_2.CommandArgOutput];
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const deployments = {};
    const outputPlans = await Promise.all((await apiClient.getPlans({
        organization_id: workspaceId,
        limit,
    })).map(async (plan) => {
        let applicationId;
        const deploymentId = plan.deployment_ids?.[0] ?? plan.deployment_id;
        if (deploymentId) {
            let deployment = deployments[deploymentId];
            if (!deployment) {
                deployment = await apiClient.getDeploymentEntity(deploymentId);
                deployments[deploymentId] = deployment;
            }
            applicationId = deployment.application_id;
        }
        return {
            application_id: applicationId,
            created_time: plan.created_time,
            id: plan.id,
            labels: (plan.labels ?? []).map((label) => label.name),
            name: plan.name,
        };
    }));
    switch (output) {
        case constants_1.OutputFormats.Json:
            loggingProvider_1.logger.info(JSON.stringify(outputPlans, null, 2));
            break;
        case constants_1.OutputFormats.Yaml:
            loggingProvider_1.logger.info((0, js_yaml_1.dump)(outputPlans));
            break;
        case constants_1.OutputFormats.Table:
        default:
            printPlansAsTable(outputPlans);
            loggingProvider_1.logger.info(`${outputPlans.length} plans returned`);
            if (outputPlans.length === limit) {
                loggingProvider_1.logger.info(`... use the --limit flag to return a larger set`);
            }
            break;
    }
    return outputPlans.length;
}
function printPlansAsTable(plans) {
    const table = new cli_table3_1.default({
        head: ['ID', 'Application ID', 'Name', 'Labels', 'Created time'],
        wordWrap: true,
    });
    plans.forEach((plan) => {
        table.push([
            { rowSpan: 1, content: plan.id, vAlign: 'center' },
            { rowSpan: 1, content: plan.application_id, vAlign: 'center' },
            { rowSpan: 1, content: plan.name, vAlign: 'center' },
            { rowSpan: 1, content: plan.labels.join(', '), vAlign: 'center' },
            {
                rowSpan: 1,
                content: moment.utc(plan.created_time).format(constants_1.ListTimeFormat),
                vAlign: 'center',
            },
        ]);
    });
    loggingProvider_1.logger.info(table.toString());
}
