"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const cli_table3_1 = __importDefault(require("cli-table3"));
const moment = require("moment");
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const util_1 = require("../../commandUtil/util");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const constants_1 = require("@mablhq-internal/runtime/core/constants");
const constants_2 = require("../../constants");
const loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
const js_yaml_1 = require("js-yaml");
exports.command = 'list';
exports.describe = 'List link agents';
exports.builder = (yargs) => {
    yargs
        .option(constants_1.CommandArgWorkspaceId, {
        alias: constants_2.CommandArgAliases.WorkspaceId,
        describe: 'Workspace for which to list link agents',
        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 link agents to return',
        default: 10,
        nargs: 1,
        type: 'number',
    })
        .option(constants_2.CommandArgMaxHeartbeatAge, {
        describe: 'Only returns link agents that have sent a heartbeat within this number of seconds',
        default: 300,
        nargs: 1,
        type: 'number',
    });
};
exports.handler = (0, cliUtil_1.failWrapper)(listLinkAgents);
async function listLinkAgents(parsed) {
    const limit = parsed.limit;
    const maxHeartbeatAgeSeconds = parsed[constants_2.CommandArgMaxHeartbeatAge];
    const workspaceId = await (0, util_1.getWorkspaceId)(parsed);
    const output = parsed[constants_2.CommandArgOutput];
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const linkAgents = (await apiClient.getLinkAgentsWithRecentHeartbeats(workspaceId, limit, maxHeartbeatAgeSeconds)).map((linkAgent) => ({
        address: linkAgent.address,
        created_time: linkAgent.created_time,
        hostname: linkAgent.hostname,
        id: linkAgent.id,
        is_connected: linkAgent.is_connected,
        java_version: linkAgent.java_version,
        last_heartbeat_time: linkAgent.last_heartbeat_time,
        name: linkAgent.label,
        operating_system_architecture: linkAgent.operating_system_architecture,
        operating_system_name: linkAgent.operating_system_name,
        operating_system_version: linkAgent.operating_system_version,
        status: linkAgent.status,
        version: linkAgent.version,
    }));
    switch (output) {
        case constants_1.OutputFormats.Json:
            loggingProvider_1.logger.info(JSON.stringify(linkAgents, null, 2));
            break;
        case constants_1.OutputFormats.Yaml:
            loggingProvider_1.logger.info((0, js_yaml_1.dump)(linkAgents));
            break;
        case constants_1.OutputFormats.Table:
        default:
            printLinkAgentsAsTable(linkAgents);
            loggingProvider_1.logger.info(`${linkAgents.length} link agents returned`);
            if (linkAgents.length === limit) {
                loggingProvider_1.logger.info(`... use the --limit flag to return a larger set`);
            }
            break;
    }
    return linkAgents.length;
}
function printLinkAgentsAsTable(linkAgents) {
    const table = new cli_table3_1.default({
        head: [
            'ID',
            'Name',
            'Connected',
            'Status',
            'Host',
            'OS',
            'Java',
            'Created',
            'Heartbeat',
            'Version',
        ],
        wordWrap: true,
    });
    linkAgents.forEach((agent) => {
        table.push([
            { rowSpan: 1, content: agent.id, vAlign: 'center' },
            { rowSpan: 1, content: agent.name, vAlign: 'center' },
            { rowSpan: 1, content: agent.is_connected, vAlign: 'center' },
            { rowSpan: 1, content: agent.status, vAlign: 'center' },
            {
                rowSpan: 1,
                content: `${agent.hostname} (${agent.address})`,
                vAlign: 'center',
            },
            {
                rowSpan: 1,
                content: `${agent.operating_system_name} ${agent.operating_system_version} (${agent.operating_system_architecture})`,
                vAlign: 'center',
            },
            { rowSpan: 1, content: agent.java_version, vAlign: 'center' },
            {
                rowSpan: 1,
                content: moment.utc(agent.created_time).format(constants_1.ListTimeFormat),
                vAlign: 'center',
            },
            {
                rowSpan: 1,
                content: moment.utc(agent.last_heartbeat_time).format(constants_1.ListTimeFormat),
                vAlign: 'center',
            },
            { rowSpan: 1, content: agent.version, vAlign: 'center' },
        ]);
    });
    loggingProvider_1.logger.info(table.toString());
}
