"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const contracts_1 = require("../../../apis/codiac-api/contracts");
const contracts_2 = require("@codiac.io/codiac-common/contracts");
const command_base_exec_tenant_1 = require("../../../command-base-exec-tenant");
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");
class ImageRegistryPullSecretUnset extends command_base_exec_tenant_1.CommandBaseExecTenant {
    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;
    }
    // --------------------------------------------------------------------
    captureArgs() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { flags } = yield this.parse(ImageRegistryPullSecretUnset);
            let partial = {};
            if (flags.registry)
                partial.regCode = flags.registry;
            partial.isPrimary = (flags.item !== "secondary");
            return [partial, false];
        });
    }
    buildCandidate_silently(partial, rootMap) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!partial.regCode)
                throw new Error("A registry code must be set");
            let registries = yield this._codiacApi.ImageRegistry.readMany({ all: true }, { throwNotFound: false });
            let registry = registries.find(r => r.code === partial.regCode);
            if (!registry) {
                throw new Error(`No ImageRegistry record currently exists with code: [${partial.regCode}]. You might need to check your spelling or capture your image registry.`);
            }
            return { isPrimary: (_a = partial.isPrimary) !== null && _a !== void 0 ? _a : true, regCode: partial.regCode, registry };
        });
    }
    buildCandidate_interactively(partial, takeDefaults, rootMap) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            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.`);
            cloud_resource_configurator_factory_1.RegistryConfiguratorFactory.bootstrap(this.ioc);
            let p = {
                isPrimary: (_a = partial.isPrimary) !== null && _a !== void 0 ? _a : true,
                regCode: partial.regCode,
            };
            let candidate;
            let confirmed;
            while (!confirmed) {
                console.clear();
                // REGISTRY  (we've already gated this method for registries.length > 0)
                let keepRegistry = false;
                let selectedRegistry;
                while (keepRegistry === false) {
                    keepRegistry = (p.regCode === undefined) ? false : yield this._ui.promptConfirm("keepRegistry", `${this._styler.hilite(p.regCode)} pull secret`);
                    if (!keepRegistry) {
                        selectedRegistry = (yield this.uiRegistry.promptForExistingRegistry(contracts_1.PackageType.container, false, registries));
                        p.regCode = selectedRegistry.code;
                        keepRegistry = true;
                    }
                    // PRIMARY/SECONDARY
                    let choices = [];
                    if ((selectedRegistry === null || selectedRegistry === void 0 ? void 0 : selectedRegistry.pullSecret) !== undefined && (selectedRegistry === null || selectedRegistry === void 0 ? void 0 : selectedRegistry.pullSecret) !== null) {
                        choices.push({ name: "Primary", value: true });
                    }
                    if ((selectedRegistry === null || selectedRegistry === void 0 ? void 0 : selectedRegistry.pullSecretSecondary) !== undefined && (selectedRegistry === null || selectedRegistry === void 0 ? void 0 : selectedRegistry.pullSecretSecondary) !== null) {
                        choices.push({ name: "Secondary", value: false });
                    }
                    if (choices.length > 1) {
                        p.isPrimary = (_b = p.isPrimary) !== null && _b !== void 0 ? _b : true;
                        let keepPrimary = yield this._ui.promptConfirm("keepPrimary", `${this._styler.hilite(p.isPrimary ? "Primary" : "Secondary")} pull secret`);
                        if (!keepPrimary) {
                            p.isPrimary = (yield this._ui.promptSelect("isPrimary", "Which pull secret?: ", [{ name: "Primary", value: true }, { name: "Secondary", value: false }]));
                        }
                    }
                    else if (choices.length === 1) {
                        if (p.isPrimary && choices[0].name !== "Primary") {
                            this._ui.userMessage(this._styler.colorWarning(`The image registry [${selectedRegistry === null || selectedRegistry === void 0 ? void 0 : selectedRegistry.code}] has no primary pull secret set.`));
                            p.isPrimary = false; // switch to secondary
                        }
                        if (p.isPrimary === false && choices[0].name !== "Secondary") {
                            this._ui.userMessage(this._styler.colorWarning(`The image registry [${selectedRegistry === null || selectedRegistry === void 0 ? void 0 : selectedRegistry.code}] has no secondary pull secret set.`));
                            p.isPrimary = true; // switch to primary
                        }
                    }
                    else if (choices.length === 0) {
                        this._ui.userMessage(this._styler.colorWarning(`The ${selectedRegistry === null || selectedRegistry === void 0 ? void 0 : selectedRegistry.type} image registry [${selectedRegistry === null || selectedRegistry === void 0 ? void 0 : selectedRegistry.code}] has no pull secrets set.`));
                        if (registries.length > 1) {
                            this._ui.userMessage(`Choose another registry (or hit CTRL-C to cancel)...`);
                        }
                        else {
                            this.exit();
                        }
                        keepRegistry = false;
                        p.regCode = undefined;
                    }
                }
                let registry = registries.find(r => r.code === p.regCode);
                candidate = { isPrimary: p.isPrimary, regCode: p.regCode, registry };
                this._ui.userMessage(`You are about to remove the ${this._styler.hilite(candidate.isPrimary ? "primary" : "secondary")} pull secret for ${this._styler.bold(this._styler.hilite(candidate.regCode))} [Tenant: ${this._userCntx.currentTenantCode}].`);
                confirmed = yield this._ui.promptConfirm("confirmPullSecret", "Continue?", false);
            }
            if (candidate === undefined)
                throw new Error("No PullSecret was defined.");
            return candidate;
        });
    }
    buildCommandString(candidate, cmd) {
        cmd.push("--registry", candidate.regCode);
        if (!candidate.isPrimary)
            cmd.push("--item", "secondary");
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let pullSecretField = candidate.isPrimary ? "pullSecret" : "pullSecretSecondary";
            let patchSpec = {
                id: candidate.registry.id,
                operations: [
                    {
                        op: contracts_2.patchOperationType.replace,
                        path: pullSecretField,
                        value: undefined
                    }
                ]
            };
            let result = yield this._codiacApi.ImageRegistry.tryPatch(patchSpec);
            if (result.success) {
                this._ui.userMessage(`Successfully removed ${this._styler.hilite(candidate.isPrimary ? "primary" : "secondary")} pull secret on ${candidate.registry.type} image registry [${this._styler.hilite(candidate.registry.code)}]`);
            }
            else if (result.error) {
                this._ui.userMessage(`${this._styler.colorCritical("Error")} removing ${candidate.isPrimary ? "primary" : "secondary"} pull secret on ${candidate.registry.type} image registry [${candidate.registry.code}]: ${result.error.name} ${(_a = result.error.message) !== null && _a !== void 0 ? _a : result.error.stack}`);
            }
        });
    }
}
exports.default = ImageRegistryPullSecretUnset;
ImageRegistryPullSecretUnset.description = 'Removes the primary or secondary pull secret reference for the given container registry.';
ImageRegistryPullSecretUnset.aliases = ['pullsecret:unset'];
ImageRegistryPullSecretUnset.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    registry: core_1.Flags.string({ char: 'r', required: false, exclusive: ["kit"], description: "The container registry in which the image exists (defaults to docker hub)." }),
    item: core_1.Flags.string({ char: 'f', options: ["primary", "secondary"], required: false, default: "primary", description: "Applies the command to either the primary (default) or secondary secret for the image registry." }),
    silent: core_1.Flags.boolean({ exclusive: ["echo", "to-script"], description: 'Executes without any user interaction; fails on missing or invalid arguments.' }),
    echo: core_1.Flags.boolean({ exclusive: ["to-script", "silent"], description: 'Renders the equivalent non-interactive command for future use before executing.' }),
    "to-script": core_1.Flags.boolean({ exclusive: ["echo", "silent"], description: 'Renders the equivalent non-interactive command without executing it.' }),
};
ImageRegistryPullSecretUnset.args = {};
//# sourceMappingURL=unset.js.map