"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 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");
const type_safety_utils_1 = require("../../uilogic/type-safety-utils");
class ImageRegistryCapture 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(ImageRegistryCapture);
            let partial = {};
            if (flags.url)
                partial.url = flags.url;
            if (flags.provider)
                partial.provider = type_safety_utils_1.TypeSafetyUtils.toEnum(contracts_1.CloudProviderEnum, flags.provider);
            if (flags.name)
                partial.code = flags.name;
            return [partial, false];
        });
    }
    buildCandidate_silently(partial, rootMap) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            throw new Error(`Silent capture not yet implemented`);
        });
    }
    buildCandidate_interactively(partial, takeDefaults, rootMap) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (partial.code) {
                let alreadyCaptured = yield this._codiacApi.ImageRegistry.readMany({ all: true }, { throwNotFound: false });
                let found = alreadyCaptured.find(r => r.code === partial.code);
                if (found)
                    throw new Error(`Image registry [${partial.code}] already exists as [${found.type}, url: ${found.url}]`);
            }
            cloud_resource_configurator_factory_1.RegistryConfiguratorFactory.bootstrap(this.ioc);
            let registry = (yield this.uiRegistry.promptForRegistry(contracts_1.PackageType.container, this.ioc, partial, true));
            registry.pullRequiresAuth = type_safety_utils_1.TypeSafetyUtils.toBoolean((_a = registry.pullRequiresAuth) !== null && _a !== void 0 ? _a : true);
            registry.pullRequiresAuth = yield this._ui.promptConfirm("reqAuth", "Is it private (requires authentication to pull images)?", registry.pullRequiresAuth);
            return registry;
        });
    }
    buildCommandString(candidate, cmd) {
        if (candidate.code)
            cmd.push("--name", candidate.code);
        if (candidate.provider)
            cmd.push("--provider", candidate.provider);
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                let minted = yield this._codiacApi.ImageRegistry.create(candidate);
                this.logger.debug(`Successfully captured ${candidate.type} image registry [${this._styler.hilite(candidate.code)}]`, minted);
                this._ui.userMessage(`Successfully captured ${candidate.type} image registry [${this._styler.hilite(candidate.code)}]`);
            }
            catch (err) {
                this._ui.userMessage(`${this._styler.colorCritical("Error")} capturing ${candidate.type} image registry [${candidate.code}]: ${err.name} ${(_a = err.message) !== null && _a !== void 0 ? _a : err.stack}`);
                this.logger.error(err, candidate);
                throw err;
            }
        });
    }
}
exports.default = ImageRegistryCapture;
ImageRegistryCapture.description = 'Saves a reference to an existing container registry.';
ImageRegistryCapture.aliases = [];
ImageRegistryCapture.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    url: core_1.Flags.string({ char: 'u', required: false, description: "The container registry url." }),
    provider: core_1.Flags.string({ char: 'p', options: Object.values(contracts_1.CloudProviderEnum), required: false, description: "The cloud provider hosting the container registry." }),
    name: core_1.Flags.string({ char: 'n', required: false, description: "The resource name of the container registry within the cloud provider subscription." }),
    subscriptionId: core_1.Flags.string({ char: 's', required: false, description: "The id of the cloud provider account in which the registry resides." }),
    location: core_1.Flags.string({ char: 'l', required: false, description: "The data center in which the registry resides (use the code name, eg: in Aws use 'us-east-1', NOT 'Virginia, US')." }),
    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.' }),
};
ImageRegistryCapture.args = {};
//# sourceMappingURL=capture.js.map