"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const _ = require("lodash");
const codiac_relay_contracts_1 = require("@codiac.io/codiac-relay-contracts");
const ops_1 = require("../ops");
const command_base_tenantless_1 = require("../command-base-tenantless");
class Identity extends command_base_tenantless_1.CommandBaseTenantless /* TODO: extend CommandBaseEnterprise */ {
    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(Identity);
                    let identityHandler = new ops_1.IdentityAggregator(this._projectRoot, this.logger);
                    if (!identityHandler)
                        throw new Error(`Cannot continue: No default identity handler has been registered to support the given identity.`);
                    // @ts-ignore <-- BYG: HACK, just pulled and wanted a clean build.  Have no idea what the failure or fix is.
                    let identity = identityHandler.createIdentity(flags.provider, flags.token, flags);
                    if (!this._projUserCfg.identitySet)
                        this._projUserCfg.identitySet = {};
                    if (this._projUserCfg.identitySet[identity.tokenName]) {
                        let ok = yield this._ui.promptConfirm("overwriteIdentity", `Identity [${this._styler.hilite(identity.tokenName)}] already exists.  Overwrite? (y/n) `);
                        if (!ok) {
                            this.logger.notice("Operation cancelled.  No work was done.");
                            this._ui.userMessage("Operation cancelled.  No work was done.");
                            this.exit(0);
                        }
                    }
                    this._projUserCfg.identitySet[identity.tokenName] = identity;
                    this.projCfgRepo.writeProjectUserConfig(this._projUserCfg); // <--- HEY!! this shouldnt be synchronous
                    this.logger.notice(`Stored tokenized identity [${this._styler.hilite(identity.tokenName)}]`, JSON.stringify(identity, undefined, 2));
                    this._ui.userMessage(`Stored tokenized identity [${this._styler.hilite(identity.tokenName)}]`);
                    // When this is moved to stateful service, invert this to an event-based model.
                    yield identityHandler.syncIdentities(this._projUserCfg.identitySet);
                    // if (identity.provider == IdentityProvider.npm) {
                    //   let npmIdentities = <TokenizedIdentity[]>_.values(_.pickBy(this._userCfg.identitySet,
                    //     x => x.provider == IdentityProvider.npm || x.provider == IdentityProvider.azart));
                    //   await this._ops.npmSyncIdentitiesWithNpmrc(...npmIdentities);
                    // }
                    // Write the registries to the project config
                    let regs = _.values(this._projUserCfg.identitySet)
                        .map(id => codiac_relay_contracts_1.RegistryReference.fromIdentity(id));
                    this._projCfg.requiredIdentities = regs;
                    yield this.projCfgRepo.updateProjectConfigFile(this._projCfg);
                    resolve();
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
}
exports.default = Identity;
Identity.description = 'Stores an identity token for the current user, for use with a component tool (such as npm).  This command acts as an upsert.';
Identity.aliases = ['identify', 'token'];
Identity.NPM_PROVIDER = codiac_relay_contracts_1.IdentityProvider.npm;
Identity.NPM_REGISTRY_URL = "//registry.npmjs.org/";
Identity.flags = {
    help: core_1.Flags.help({ char: 'h', description: 'Renders the help document for this command.' }),
    provider: core_1.Flags.string({
        char: 'p', required: false, default: Identity.NPM_PROVIDER,
        options: [...ops_1.IdentityHandlerRegistry.supportedProviders], description: 'The source of the token.'
    }),
    scope: core_1.Flags.string({ char: 's', required: false, description: 'The subdivision within the registry for which this token is honored.' }),
    registryUrl: core_1.Flags.string({ char: 'r', required: false, description: 'The component tool that issued and can consume the token.' }),
    token: core_1.Flags.string({ char: 't', required: true, description: 'The actual raw token string itself issued by the provider' }),
    organization: core_1.Flags.string({ char: 'g', required: false, dependsOn: ["email", "feed"], description: '(Azure Artifacts [aka: azart] only) Human readable identifier for the organization account with the provider.' }),
    feed: core_1.Flags.string({ char: 'f', required: false, dependsOn: ["organization", "email"], description: '(Azure Artifacts [aka: azart] only) The human readable identifier for the package feed' }),
    email: core_1.Flags.string({ char: 'e', required: false, dependsOn: ["organization", "feed"], description: '(Azure Artifacts [aka: azart] only) The email address for this identity.  Npm requires for this, but never uses it.' })
};
Identity.args = {
    tokenName: core_1.Args.string({ required: false, description: '(optional) Conventional name (token_for_[provider]_[scope]) for the tokenized identity.  This name will also be used for the build environment variable carrying the token.' })
};
//# sourceMappingURL=identity.js.map