"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const rimraf = require("rimraf-then");
const binify_1 = require("./binify");
const safeReadPkg_1 = require("./fs/safeReadPkg");
const loggers_1 = require("./loggers");
function removeTopDependency(dependency, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        const results = yield Promise.all([
            removeBins(dependency.name, opts),
            !opts.dryRun && rimraf(path.join(opts.modules, dependency.name)),
        ]);
        const uninstalledPkg = results[0];
        if (!opts.muteLogs) {
            loggers_1.rootLogger.info({
                removed: {
                    dependencyType: dependency.dev && 'dev' || dependency.optional && 'optional' || 'prod',
                    name: dependency.name,
                    version: uninstalledPkg && uninstalledPkg.version,
                },
            });
        }
    });
}
exports.default = removeTopDependency;
function removeBins(uninstalledPkg, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        const uninstalledPkgPath = path.join(opts.modules, uninstalledPkg);
        const uninstalledPkgJson = yield safeReadPkg_1.fromDir(uninstalledPkgPath);
        if (!uninstalledPkgJson)
            return;
        const cmds = yield binify_1.default(uninstalledPkgJson, uninstalledPkgPath);
        if (!opts.dryRun) {
            yield Promise.all(cmds.map((cmd) => path.join(opts.bin, cmd.name)).map(rimraf));
        }
        return uninstalledPkgJson;
    });
}
//# sourceMappingURL=removeTopDependency.js.map