"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const path = require("path");
const core_1 = require("@oclif/core");
const inquirer = require("inquirer");
const command_base_tenantless_1 = require("../../command-base-tenantless");
class DepSource extends command_base_tenantless_1.CommandBaseTenantless {
    run() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    this.bootstrap();
                    const { args, flags } = yield this.parse(DepSource);
                    let projectRoot = this._projectRoot; //.getConfigRoot();
                    let pkgName;
                    let select = false;
                    let names = yield this._ops.getNpmDependencies(projectRoot);
                    if (!args.name || names.indexOf(args.name) < 0) {
                        let result = yield inquirer.prompt({ type: 'list', name: 'name', message: 'dependency to edit:', choices: names });
                        // Commented out because there is no empty response. (user can only cancel process or choose)
                        // if (!result.name) {
                        //   this._ui.userMessage("Operation cancelled: No work was done.");
                        //   this.exit(0);
                        // } else {
                        pkgName = result.name;
                        // }
                    }
                    else {
                        pkgName = args.name;
                    }
                    let distSubPath;
                    if (flags.distSubPath) {
                        distSubPath = flags.distSubPath;
                    }
                    else {
                        distSubPath = yield this._ui.prompt("distSubPath", "Enter the sub-path to the dist folder for the package.  (Enter for the repo root)", true, undefined);
                    }
                    let depFolder = path.join(projectRoot, "node_modules", pkgName);
                    let pkg = this._ops.readNpmPackageJson(depFolder);
                    // get the repoUrl for the dependency from its package.json
                    this.logger.debug(JSON.stringify(pkg));
                    if (pkg) {
                        if (pkg.repository == undefined || pkg.repository == "" || pkg.repository.url == undefined || pkg.repository.url == "") {
                            throw new Error(`Cannot source ${pkgName} because it has no repository url declared in its package definition.`);
                        }
                        else {
                            let cloneUrl = pkg.repository.url;
                            // NOTE: Need to parse out any npm prefix on the url:  git+http://  or xyz+http://.  
                            let ptn = /^(?:[^:]+\+)/; // Matches a "something+" prefix to the protocol specifier
                            cloneUrl = cloneUrl.replace(ptn, "");
                            // Use toyhauler-auth-contracts to test
                            let pkgVersion = pkg.version;
                            this._ui.userMessage(`pkg: ${pkgName}, cloneUrl: ${cloneUrl}, lastUsedVersion: ${pkgVersion}`);
                            let subm = yield this._ops.addSubmodule(cloneUrl, pkgName, pkgVersion);
                            subm.distributionRoot = distSubPath;
                            yield this._ops.symLinkSubmodule(subm);
                        }
                    }
                    else {
                        throw new Error(`Cannot source ${pkgName} because it has no package definition file.`);
                    }
                    resolve();
                }
                catch (err) {
                    this.handleError(err);
                    reject(err);
                }
            }));
        });
    }
}
exports.default = DepSource;
DepSource.description = 'Loads the source code for the given dependency';
DepSource.aliases = ['dep:src'];
DepSource.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    distSubPath: core_1.Flags.string({ char: 'd', description: "Subfolder path, relative to the root of the submodule,  to the folder from which the package is created,  aka: the build output folder or 'dist' folder (eg: bin, dist, or lib, ...etc).  This folder is used as the target folder for npm link." })
};
DepSource.args = {
    name: core_1.Args.string({ description: 'The official unique name of the dependency package.' })
};
//# sourceMappingURL=source.js.map