"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.upgradeInteractive = exports.UI_GROUPS = void 0;
// UI Code, Table creation, and choice layout leveraged from npm-check
// https://github.com/dylang/npm-check/blob/master/lib/out/interactive-update.js
// Extended to use one type of text table
const inquirer_1 = __importDefault(require("inquirer"));
const cli_table_1 = __importDefault(require("cli-table"));
const terminal_1 = require("@rushstack/terminal");
function greenUnderlineBold(text) {
    return terminal_1.Colorize.underline(terminal_1.Colorize.bold(terminal_1.Colorize.green(text)));
}
function yellowUnderlineBold(text) {
    return terminal_1.Colorize.underline(terminal_1.Colorize.bold(terminal_1.Colorize.yellow(text)));
}
function redUnderlineBold(text) {
    return terminal_1.Colorize.underline(terminal_1.Colorize.bold(terminal_1.Colorize.red(text)));
}
function magentaUnderlineBold(text) {
    return terminal_1.Colorize.underline(terminal_1.Colorize.bold(terminal_1.Colorize.magenta(text)));
}
exports.UI_GROUPS = [
    {
        title: greenUnderlineBold('Update package.json to match version installed.'),
        filter: { mismatch: true, bump: undefined }
    },
    {
        title: `${greenUnderlineBold('Missing.')} ${terminal_1.Colorize.green('You probably want these.')}`,
        filter: { notInstalled: true, bump: undefined }
    },
    {
        title: `${greenUnderlineBold('Patch Update')} ${terminal_1.Colorize.green('Backwards-compatible bug fixes.')}`,
        filter: { bump: 'patch' }
    },
    {
        title: `${yellowUnderlineBold('Minor Update')} ${terminal_1.Colorize.yellow('New backwards-compatible features.')}`,
        bgColor: 'yellow',
        filter: { bump: 'minor' }
    },
    {
        title: `${redUnderlineBold('Major Update')} ${terminal_1.Colorize.red('Potentially breaking API changes. Use caution.')}`,
        filter: { bump: 'major' }
    },
    {
        title: `${magentaUnderlineBold('Non-Semver')} ${terminal_1.Colorize.magenta('Versions less than 1.0.0, caution.')}`,
        filter: { bump: 'nonSemver' }
    }
];
function label(dep) {
    const bumpInstalled = dep.bump ? dep.installed : '';
    const installed = dep.mismatch ? dep.packageJson : bumpInstalled;
    const name = terminal_1.Colorize.yellow(dep.moduleName);
    const type = dep.devDependency ? terminal_1.Colorize.green(' devDep') : '';
    const missing = dep.notInstalled ? terminal_1.Colorize.red(' missing') : '';
    const homepage = dep.homepage ? terminal_1.Colorize.blue(terminal_1.Colorize.underline(dep.homepage)) : '';
    return [
        name + type + missing,
        installed,
        installed && '>',
        terminal_1.Colorize.bold(dep.latest || ''),
        dep.latest ? homepage : getErrorDep(dep)
    ];
}
function getErrorDep(dep) {
    if (dep.regError !== undefined && dep.regError && dep.regError instanceof Error) {
        return dep.regError.message;
    }
    else if (dep.pkgError !== undefined && dep.pkgError && dep.pkgError instanceof Error) {
        return dep.pkgError.message;
    }
    return '';
}
function short(dep) {
    return `${dep.moduleName}@${dep.latest}`;
}
function getChoice(dep) {
    if (!dep.mismatch && !dep.bump && !dep.notInstalled) {
        return false;
    }
    return {
        value: dep,
        name: label(dep),
        short: short(dep)
    };
}
function unselectable(options) {
    return new inquirer_1.default.Separator(terminal_1.AnsiEscape.removeCodes(options ? options.title : ''));
}
function createChoices(packages, options) {
    const { filter } = options;
    const filteredChoices = packages.filter((pkg) => {
        if ('mismatch' in filter && pkg.mismatch !== filter.mismatch) {
            return false;
        }
        else if ('bump' in filter && pkg.bump !== filter.bump) {
            return false;
        }
        else if ('notInstalled' in filter && pkg.notInstalled !== filter.notInstalled) {
            return false;
        }
        else {
            return true;
        }
    });
    const choices = filteredChoices
        .map(getChoice)
        .filter(Boolean);
    const cliTable = new cli_table_1.default({
        chars: {
            top: '',
            'top-mid': '',
            'top-left': '',
            'top-right': '',
            bottom: '',
            'bottom-mid': '',
            'bottom-left': '',
            'bottom-right': '',
            left: '',
            'left-mid': '',
            mid: '',
            'mid-mid': '',
            right: '',
            'right-mid': '',
            middle: ' '
        },
        colWidths: [50, 10, 3, 10, 100]
    });
    for (const choice of choices) {
        if (typeof choice === 'object' && 'name' in choice) {
            cliTable.push(choice.name);
        }
    }
    const choicesAsATable = cliTable.toString().split('\n');
    for (let i = 0; i < choices.length; i++) {
        const choice = choices[i];
        if (typeof choice === 'object' && 'name' in choice) {
            choice.name = choicesAsATable[i];
        }
    }
    if (choices.length > 0) {
        choices.unshift(unselectable(options));
        choices.unshift(unselectable());
        return choices;
    }
}
const upgradeInteractive = async (pkgs) => {
    const choicesGrouped = exports.UI_GROUPS.map((group) => createChoices(pkgs, group)).filter(Boolean);
    const choices = [];
    for (const choiceGroup of choicesGrouped) {
        if (choiceGroup) {
            choices.push(...choiceGroup);
        }
    }
    if (!choices.length) {
        // eslint-disable-next-line no-console
        console.log('All dependencies are up to date!');
        return { packages: [] };
    }
    choices.push(unselectable());
    choices.push(unselectable({ title: 'Space to select. Enter to start upgrading. Control-C to cancel.' }));
    const promptQuestions = [
        {
            name: 'packages',
            message: 'Choose which packages to upgrade',
            type: 'checkbox',
            choices: choices.concat(unselectable()),
            pageSize: process.stdout.rows - 2
        }
    ];
    const answers = (await inquirer_1.default.prompt(promptQuestions));
    return answers;
};
exports.upgradeInteractive = upgradeInteractive;
//# sourceMappingURL=InteractiveUpgradeUI.js.map