"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const read_importer_manifest_1 = require("@pnpm/read-importer-manifest");
const npa = require("@zkochan/npm-package-arg");
const dependencies_hierarchy_1 = require("dependencies-hierarchy");
const renderJson_1 = require("./renderJson");
const renderParseable_1 = require("./renderParseable");
const renderTree_1 = require("./renderTree");
const DEFAULTS = {
    alwaysPrintRootPackage: true,
    depth: 0,
    long: false,
    registries: undefined,
    reportAs: 'tree',
};
async function forPackages(packages, projectPath, maybeOpts) {
    const opts = Object.assign({}, DEFAULTS, maybeOpts);
    const searched = packages.map((arg) => {
        const parsed = npa(arg);
        if (parsed.raw === parsed.name) {
            return parsed.name;
        }
        if (parsed.type !== 'version' && parsed.type !== 'range') {
            throw new Error(`Invalid argument - ${arg}. List can search only by version or range`);
        }
        return {
            name: parsed.name,
            range: parsed.fetchSpec,
        };
    });
    const tree = await dependencies_hierarchy_1.forPackages(searched, projectPath, {
        depth: opts.depth,
        include: maybeOpts && maybeOpts.include,
        lockfileDirectory: maybeOpts && maybeOpts.lockfileDirectory,
        registries: opts.registries,
    });
    const print = getPrinter(opts.reportAs);
    const entryPkg = await read_importer_manifest_1.readImporterManifestOnly(projectPath);
    return print({
        name: entryPkg.name,
        path: projectPath,
        version: entryPkg.version,
    }, tree, {
        alwaysPrintRootPackage: opts.alwaysPrintRootPackage,
        depth: opts.depth,
        long: opts.long,
        search: Boolean(packages.length),
    });
}
exports.forPackages = forPackages;
async function default_1(projectPath, maybeOpts) {
    const opts = Object.assign({}, DEFAULTS, maybeOpts);
    const tree = opts.depth === -1
        ? {}
        : await dependencies_hierarchy_1.default(projectPath, {
            depth: opts.depth,
            include: maybeOpts && maybeOpts.include,
            lockfileDirectory: maybeOpts && maybeOpts.lockfileDirectory,
            registries: opts.registries,
        });
    const print = getPrinter(opts.reportAs);
    const entryPkg = await read_importer_manifest_1.readImporterManifestOnly(projectPath);
    return print({
        name: entryPkg.name,
        path: projectPath,
        version: entryPkg.version,
    }, tree, {
        alwaysPrintRootPackage: opts.alwaysPrintRootPackage,
        depth: opts.depth,
        long: opts.long,
        search: false,
    });
}
exports.default = default_1;
function getPrinter(reportAs) {
    switch (reportAs) {
        case 'parseable': return renderParseable_1.default;
        case 'json': return renderJson_1.default;
        case 'tree': return renderTree_1.default;
    }
}
