"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.printTable = exports.isFlatTableRowNormal = exports.flattenTable = void 0;
const util_1 = require("./util");
const text_1 = require("./text");
const constants_1 = require("./constants");
;
function flattenTable(table) {
    const rows = !table
        ? []
        : !Array.isArray(table)
            ? [table]
            : table;
    return [].concat(...rows
        .map(obj => Object.keys(obj)
        .map(key => ({ key, desc: util_1.arrayify(obj[key]) }))));
}
exports.flattenTable = flattenTable;
function isFlatTableRowNormal(row) {
    return typeof row.header === 'undefined';
}
exports.isFlatTableRowNormal = isFlatTableRowNormal;
function getFirstWidth(rows) {
    return rows
        .filter(isFlatTableRowNormal)
        .map(row => row.group
        ? constants_1.groupIndent + row.key.length
        : row.key.length)
        .sort((a, b) => b - a)[0];
}
function getSecondWidth(rows) {
    const allRows = ([]);
    return Math.max(...rows
        .filter(isFlatTableRowNormal)
        .map(row => Math.max(...row.desc.map(line => line.length), ...(!row.getExtraDescriptionRows ? [] :
        row.getExtraDescriptionRows()
            .map(line => line.length)))));
}
function printTable(indent, rows) {
    const width = getFirstWidth(rows);
    const descWidth = width + constants_1.gapLength + getSecondWidth(rows);
    const prefix = " ".repeat(indent);
    const groupPrefix = " ".repeat(constants_1.groupIndent);
    const gap = " ".repeat(constants_1.gapLength);
    const widenLine = text_1.makeWidenRight(descWidth);
    const ret = rows.map((row) => {
        if (!isFlatTableRowNormal(row)) {
            return [row.header];
        }
        const { key, desc, group, isGroup, getExtraDescriptionRows } = row;
        const retLines = [];
        if (isGroup) {
            retLines.push(prefix +
                text_1.styledText(group, widenLine(text_1.widenRight(group.name, width) +
                    gap)));
        }
        else {
            const [first, ...rest] = desc;
            retLines.push(prefix +
                text_1.styledText(group, widenLine((group ? groupPrefix : '') +
                    text_1.widenRight(key, width - (group ? constants_1.groupIndent : 0)) +
                    gap +
                    first)));
            retLines.push(...rest.map(text => prefix +
                text_1.styledText(group, widenLine(text_1.widenRight('', width) +
                    gap +
                    text))));
            if (getExtraDescriptionRows)
                retLines.push(...getExtraDescriptionRows()
                    .map(line => prefix +
                    text_1.styledText(group, widenLine(text_1.widenRight('', width) +
                        gap +
                        line))));
        }
        return retLines;
    });
    return [].concat(...ret);
}
exports.printTable = printTable;
