"use strict";
/**
 * Copyright © 2018 Emu Analytics
 */
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handler = exports.builder = exports.desc = exports.command = void 0;
const utils_1 = require("../../utils");
exports.command = ['components <id>', 'comps <id>'];
exports.desc = 'Show pipeline components';
const builder = (args) => {
    return args.positional('id', { describe: 'Pipeline id (or unique prefix)', type: 'string' });
};
exports.builder = builder;
function handler({ client, id, format }) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const pipeline = yield (0, utils_1.resolveResource)(id, client.pipelines, 'id', ['components'], ['id', 'components.index']);
            if (!pipeline) {
                (0, utils_1.logObject)({ message: `Pipeline not found: ${id}` }, format || 'json');
                return;
            }
            const components = pipeline.components || [];
            if (format === 'json') {
                (0, utils_1.logObject)(components, 'json');
                return;
            }
            const rows = buildComponentRows(components);
            if (!rows.length) {
                (0, utils_1.logInfo)('No Components Found');
                return;
            }
            (0, utils_1.logObject)(rows, 'table', ['id', 'class', 'type', 'description', 'note']);
        }
        catch (e) {
            (0, utils_1.logError)(e);
        }
    });
}
exports.handler = handler;
/**
 * Transforms pipeline components into table rows
 */
function buildComponentRows(components) {
    if (!components.length) {
        return [];
    }
    // Make component lookup
    const componentsMap = {};
    components.forEach(c => (componentsMap[c.id] = Object.assign(Object.assign({}, c), { next: [], previous: [], indent: 0 })));
    // Assemble component topology
    Object.values(componentsMap).forEach((c) => {
        const metadata = c.metadata || {};
        const previousIds = metadata.previousComponents || [];
        const nextIds = metadata.nextComponents || [];
        c.previous = previousIds.map((id) => componentsMap[id]);
        c.next = nextIds.map((id) => componentsMap[id]);
    });
    // Group children by parent
    const childrenByParent = {};
    Object.values(componentsMap).forEach((c) => {
        const metadata = c.metadata || {};
        const parentId = metadata.parentComponent;
        if (parentId) {
            if (!childrenByParent[parentId]) {
                childrenByParent[parentId] = [];
            }
            childrenByParent[parentId].push(c);
        }
    });
    // Sort children by index
    Object.values(childrenByParent).forEach(children => {
        children.sort((a, b) => a.index - b.index);
    });
    // Find root components (no previous, not cache)
    const roots = Object.values(componentsMap).filter(c => c.class !== 'cache' && (c.previous || []).length === 0);
    // Calculate indentation via traversal
    const visited = new Set();
    function traverse(node, indent) {
        if (!node || visited.has(node.id)) {
            return;
        }
        visited.add(node.id);
        node.indent = indent;
        // Handle pipeline children
        if (node.class === 'pipeline') {
            const children = childrenByParent[node.id] || [];
            children.forEach(child => traverse(child, indent + 1));
        }
        // Handle next components
        const next = (node.next || []).filter((n) => n.class !== 'cache');
        const increaseIndent = node.type === 'fp:fork' || next.length > 1;
        next.forEach((n) => traverse(n, increaseIndent ? indent + 1 : indent));
    }
    roots.forEach(root => traverse(root, 0));
    // Render table rows
    return Object.values(componentsMap)
        .filter(c => c.class !== 'cache')
        .sort((a, b) => a.index - b.index)
        .map(c => {
        const notes = [];
        const metadata = c.metadata || {};
        const caches = metadata.caches || [];
        if (caches.length > 0) {
            notes.push(`uses cache: ${caches.join(', ')}`);
        }
        const prefix = c.indent > 0 ? '  '.repeat(c.indent) + '> ' : '';
        function formatComponentId(component) {
            if (component.class === 'pipeline') {
                return `(${component.id})`;
            }
            if (component.type === 'fp:fork') {
                return `[${component.id}]`;
            }
            return component.id;
        }
        return {
            id: prefix + formatComponentId(c),
            class: c.class,
            type: c.type,
            description: c.description,
            note: notes.join()
        };
    });
}
//# sourceMappingURL=components.js.map