"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const autocomplete = require("inquirer-autocomplete-prompt");
const command_base_enterprise_1 = require("../../command-base-enterprise");
const prettify_1 = require("../../prettify");
const cloud_provider_contextualizer_1 = require("../../uilogic/cloud-provider-contextualizer");
class SecretStoreForget extends command_base_enterprise_1.CommandBaseEnterprise {
    bootstrap() {
        super.bootstrap();
        cloud_provider_contextualizer_1.CloudProviderContextualizer.bootstrap(this.ioc);
    }
    // --------------------------------------------------------------------
    // Lazy-loaded properties
    // --------------------------------------------------------------------
    run() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                this.bootstrap();
                const { args, flags } = yield this.parse(SecretStoreForget);
                this._userCntx = yield this.establishTenantContext(this._userCntx);
                let existings = yield this._codiacApi.KvpStoreDef.readMany({ all: true }, { throwNotFound: false });
                if (existings.length === 0) {
                    throw new Error(`Cannot set pull secrets: No image registries are defined yet.`);
                }
                let candidate;
                if (flags.silent == true) {
                    candidate = this.buildCandidate_silently(flags.name, existings);
                }
                else {
                    candidate = (yield this.buildCandidate_interactively(flags.name, existings)); // TODO: Change this method to return a secretStoreDef
                }
                // FINAL EXECUTION (or not)
                if (candidate !== undefined) {
                    if (flags.toScript === true) {
                        let script = this.buildScript(candidate);
                        this._ui.userMessage(script);
                    }
                    else {
                        yield this.deleteRecord(candidate);
                    }
                }
                else {
                    this.logger.notice(`Operation cancelled. No work was done.`);
                    this._ui.userMessage(`Operation cancelled. No work was done.`);
                }
            }
            catch (err) {
                this.handleError(err);
            }
            finally {
                yield this.closeConnections();
                return;
            }
        });
    }
    buildCandidate_silently(name, registries) {
        try {
            // Rough validation for missing args
            if (!name)
                throw new Error("A name must be set");
            let found = registries.find(r => r.name === name);
            if (!found) {
                throw new Error(`No secret store record currently exists with code: [${name}]. Either it may not be captured or you might need to check your spelling.`);
            }
            return found;
        }
        catch (err) {
            throw err;
        }
    }
    /** Walks the user through a Q & A to build out the specs for the asset. */
    buildCandidate_interactively(name, existings) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                let candidate;
                try {
                    let confirmed;
                    while (!confirmed) {
                        // NOTE:  We are gating on "confirmed != undefined" because that means they asked to change their selection. 
                        let choices = existings.map((x, index) => { return { name: `${x.name} (${x.type})`, value: index }; });
                        let selectedIndex = (yield this._ui.promptSelect("condemned", "Secret Store: ", choices));
                        candidate = existings[selectedIndex];
                        this._ui.userMessage((0, prettify_1.prettify)(candidate));
                        this._ui.userMessage(`You are about to remove the record for ${candidate.type} secret store ${this._styler.bold(this._styler.hilite(candidate.name))} [Tenant: ${this._userCntx.currentTenantCode}].`);
                        confirmed = yield this._ui.promptConfirm("confirm", "Continue?", false);
                    }
                    if (candidate === undefined)
                        throw new Error("No secret store was defined."); // this shd never happen; it's just here to pacify typescript.
                    resolve(candidate);
                }
                catch (err) {
                    // this.logger.error(`${err.name ?? ''} ${err.message ?? ''}`, err.stack);
                    reject(err);
                }
            }));
        });
    }
    deleteRecord(condemned) {
        return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            var _a;
            try {
                let result = yield this._codiacApi.KvpStoreDef.tryDelete({ id: condemned.id });
                if (result.success) {
                    this._ui.userMessage(`Successfully removed ${condemned.type} secret store [${this._styler.hilite(condemned.name)}]`);
                }
                else if (result.error) {
                    this._ui.userMessage(`${this._styler.colorCritical("Error")} removing ${condemned.type} secret store [${condemned.name}]: ${result.error.name} ${(_a = result.error.message) !== null && _a !== void 0 ? _a : result.error.stack}`);
                }
                resolve();
            }
            catch (err) {
                this.logger.error(err, condemned);
                resolve();
                // reject(err);
            }
        }));
    }
    buildScript(candidate) {
        let output;
        try {
            output = `codiac secretStore:forget --silent`;
            let args;
            let flags = {};
            flags.name = candidate.name;
            Object.keys(flags).forEach(k => output = output.concat(" ", `--${k}=${flags[k]}`));
            return output;
        }
        catch (err) {
            throw err;
        }
    }
}
exports.default = SecretStoreForget;
SecretStoreForget.description = 'Removes the reference to the given container registry for the tenant.  Does NOT delete the registry itself.';
SecretStoreForget.aliases = [];
SecretStoreForget.dependsOn = ["name"];
SecretStoreForget.flags = {
    name: core_1.Flags.string({ char: 'n', required: false, description: "The name of the secret store to forget." }),
    toScript: core_1.Flags.boolean({ char: 'z', required: false, description: `Outputs an assembled command string, NO execution` }),
    silent: core_1.Flags.boolean({ char: 'y', dependsOn: SecretStoreForget.dependsOn, required: false, description: `(Optional: defaults to false) Prevents confirmations of user-values that are remembered from prior runs. Requires: ${SecretStoreForget.dependsOn}` }),
    help: core_1.Flags.help({ char: 'h' })
};
SecretStoreForget.args = {};
//# sourceMappingURL=forget.js.map