"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const js_yaml_1 = require("js-yaml");
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const cli_table3_1 = __importDefault(require("cli-table3"));
const moment = require("moment");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const commandTypes_1 = require("@mablhq-internal/runtime/core/commandTypes");
const constants_1 = require("@mablhq-internal/runtime/core/constants");
const constants_2 = require("../../constants");
const loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
exports.command = 'list';
exports.describe = 'List your workspaces';
exports.builder = (yargs) => {
    yargs
        .option(constants_2.CommandArgLimitOutput, {
        alias: constants_2.CommandArgAliases.LimitOutput,
        describe: 'The number of workspaces to return',
        default: commandTypes_1.DEFAULT_LISTING_RESULT_LIMIT,
        nargs: 1,
    })
        .option(constants_2.CommandArgOutput, {
        alias: constants_2.CommandArgAliases.OutputType,
        choices: constants_2.DefaultOutputFormatChoices,
        describe: 'Specify result output format',
        nargs: 1,
    });
};
exports.handler = (0, cliUtil_1.failWrapper)(listWorkspaces);
async function listWorkspaces(parsed) {
    const output = parsed.output;
    const limit = parsed.limit;
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const workspaces = await apiClient.getWorkspaces(limit);
    printWorkspaces(workspaces, output);
    return workspaces.length;
}
function printWorkspaces(workspaces, output) {
    switch (output) {
        case 'json':
            loggingProvider_1.logger.info(JSON.stringify(workspaces, null, 2));
            break;
        case 'yaml':
            loggingProvider_1.logger.info((0, js_yaml_1.dump)(workspaces));
            break;
        default:
            const table = new cli_table3_1.default({
                head: ['ID', 'Name', 'Created time'],
                wordWrap: true,
            });
            workspaces.forEach((workspace) => {
                table.push([
                    { rowSpan: 1, content: workspace.id, vAlign: 'center' },
                    { rowSpan: 1, content: workspace.name, vAlign: 'center' },
                    {
                        rowSpan: 1,
                        content: moment.utc(workspace.created_time).format(constants_1.ListTimeFormat),
                        vAlign: 'center',
                    },
                ]);
            });
            loggingProvider_1.logger.info(table.toString());
            break;
    }
}
