"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 contracts_1 = require("../../apis/codiac-api/contracts");
const command_base_enterprise_1 = require("../../command-base-enterprise");
const prettify_1 = require("../../prettify");
const cloud_resource_configurator_factory_1 = require("../../uilogic/cloud-resource-configurator-factory");
const cloud_provider_contextualizer_1 = require("../../uilogic/cloud-provider-contextualizer");
const image_registry_contextualizer_1 = require("../../uilogic/image-registry-contextualizer");
const image_contextualizer_1 = require("../../uilogic/image-contextualizer");
// Has to be module-scoped bc the autocomplete redefines "this", so we can't use it inside searchPorts().
let ports = [];
class ImageRegistryForget extends command_base_enterprise_1.CommandBaseEnterprise {
    bootstrap() {
        super.bootstrap();
        cloud_provider_contextualizer_1.CloudProviderContextualizer.bootstrap(this.ioc);
        this.ioc.bind(image_registry_contextualizer_1.ImageRegistryContextualizer).toSelf();
        this.ioc.bind(image_contextualizer_1.ImageContextualizer).toSelf();
    }
    // --------------------------------------------------------------------
    // Lazy-loaded properties
    get uiRegistry() {
        if (this._uiRegistry_backer === undefined) {
            this._uiRegistry_backer = this.ioc.get(image_registry_contextualizer_1.ImageRegistryContextualizer);
        }
        return this._uiRegistry_backer;
    }
    // --------------------------------------------------------------------
    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(ImageRegistryForget);
                    this._userCntx = yield this.establishTenantContext(this._userCntx);
                    let registries = yield this._codiacApi.ImageRegistry.readMany({ all: true }, { throwNotFound: false });
                    if (registries.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.registry, registries);
                    }
                    else {
                        candidate = yield this.buildCandidate_interactively(flags.registry, registries);
                    }
                    // 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();
                    resolve();
                }
            }));
        });
    }
    buildCandidate_silently(regCode, registries) {
        try {
            // Rough validation for missing args
            if (!regCode)
                throw new Error("A registry code must be set");
            let found = registries.find(r => r.code === regCode);
            if (!found) {
                throw new Error(`No ImageRegistry record currently exists with code: [${regCode}]. You might need to check your spelling or capture your image registry.`);
            }
            return found;
        }
        catch (err) {
            throw err;
        }
    }
    /** Walks the user through a Q & A to build out the specs for the asset. */
    buildCandidate_interactively(regCode, registries, allowAddSecrets = false) {
        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 {
                    cloud_resource_configurator_factory_1.RegistryConfiguratorFactory.bootstrap(this.ioc);
                    let confirmed;
                    while (!confirmed) {
                        // NOTE:  We are gating on "confirmed != undefined" because that means they asked to revise the values. 
                        // console.clear();
                        // REGISTRY  (we've already gated this method for registries.length > 0)
                        candidate = (yield this.uiRegistry.promptForExistingRegistry(contracts_1.PackageType.container, false, registries));
                        this._ui.userMessage((0, prettify_1.prettify)(candidate));
                        this._ui.userMessage(`You are about to remove the record for ${candidate.type} image registry ${this._styler.bold(this._styler.hilite(candidate.code))} [Tenant: ${this._userCntx.currentTenantCode}].`);
                        confirmed = yield this._ui.promptConfirm("confirm", "Continue?", false);
                    }
                    if (candidate === undefined)
                        throw new Error("No ImageRegistry 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(registry) {
        return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            var _a;
            try {
                let result = yield this._codiacApi.ImageRegistry.tryDelete({ id: registry.id });
                if (result.success) {
                    this._ui.userMessage(`Successfully removed ${registry.type} image registry [${this._styler.hilite(registry.code)}]`);
                }
                else if (result.error) {
                    this._ui.userMessage(`${this._styler.colorCritical("Error")} removing ${registry.type} image registry [${registry.code}]: ${result.error.name} ${(_a = result.error.message) !== null && _a !== void 0 ? _a : result.error.stack}`);
                }
                resolve();
            }
            catch (err) {
                this.logger.error(err, registry);
                resolve();
                // reject(err);
            }
        }));
    }
    buildScript(candidate) {
        let output;
        try {
            output = `codiac imageRegistry:pullSecret:unset --silent`;
            let args;
            let flags = {};
            flags.registry = candidate.code;
            Object.keys(flags).forEach(k => output = output.concat(" ", `--${k}=${flags[k]}`));
            return output;
        }
        catch (err) {
            throw err;
        }
    }
}
exports.default = ImageRegistryForget;
ImageRegistryForget.description = 'Removes the reference to the given container registry for the tenant.  Does NOT delete the registry itself.';
ImageRegistryForget.aliases = [];
ImageRegistryForget.dependsOn = ["registry"];
ImageRegistryForget.flags = {
    registry: core_1.Flags.string({ char: 'r', required: false, description: "The container registry 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: ImageRegistryForget.dependsOn, required: false, description: `(Optional: defaults to false) Prevents confirmations of user-values that are remembered from prior runs. Requires: ${ImageRegistryForget.dependsOn}` }),
    help: core_1.Flags.help({ char: 'h' })
};
ImageRegistryForget.args = {};
//# sourceMappingURL=forget.js.map