"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const image_configurator_1 = require("../../uilogic/image-configurator");
const command_base_exec_tenant_1 = require("../../command-base-exec-tenant");
const prettify_1 = require("../../prettify");
const codiac_ops_common_1 = require("@codiac.io/codiac-ops-common");
class ImagesAdd extends command_base_exec_tenant_1.CommandBaseExecTenant {
    bootstrap() {
        if (ImagesAdd.isBootstrapped !== true) {
            this.requiresProjectScope = true;
            super.bootstrap();
        }
    }
    captureArgs() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { flags } = yield this.parse(ImagesAdd);
            if (this._projectRoot === undefined || this._projCfg === undefined || this._projUserCfg === undefined) {
                throw new Error(`Cannot perform image operations outside of a codiac project: Please run the "init" command from this folder to declare it as a project root.`);
            }
            return [{}, false];
        });
    }
    buildCandidate_silently(_partial, _rootMap) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            throw new Error(`This command requires interactive mode. Re-run without --silent.`);
        });
    }
    buildCandidate_interactively(_partial, _takeDefaults, _rootMap) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { args, flags } = yield this.parse(ImagesAdd);
            const credsStore = this.ioc.getNamed(codiac_ops_common_1.INTERFACES_OPS.ICredentialsStore, codiac_ops_common_1.CredentialsStoreType.DockerDesktop);
            const cfg8r = new image_configurator_1.ImageConfigurator(this._projCfg.tenantCode, this._codiacApi, this.genRelayClient, this._projCfg, this._projUserCfg, this._ui, this._styler, this._projectRoot, this.logger, credsStore, this._userCntx);
            let img;
            let confirmed = false;
            while (!confirmed) {
                img = yield cfg8r.createImage(args.imageName, flags.sourceFile, flags.port, flags.buildParams);
                console.clear();
                this._ui.userMessage((0, prettify_1.prettify)(img));
                this._ui.userMessage(`You are about to create ${img.name}. Continue?`);
                confirmed = yield this._ui.promptConfirm("confirmCreate", `(hit 'N' to edit your input)`, false);
            }
            return { img: img };
        });
    }
    buildCommandString(candidate, cmd) {
        cmd.push(candidate.img.name);
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { img } = candidate;
            const result = yield this._ops.declareImageExport(this._projCfg, img.name, img.targets[0], img.definitionFile, img.port, img.buildParams);
            if (result.image) {
                this._ui.userMessage(JSON.stringify(result.image));
                this._ui.userMessage(`Completed ${result.operation} of image export "${result.image.name}".`);
            }
            else {
                this._ui.userMessage(`Image export declaration cancelled.`);
            }
        });
    }
}
exports.default = ImagesAdd;
ImagesAdd.description = 'Configures a container image to be built and published by the project.';
ImagesAdd.aliases = ["image", "image:add", "img", "img:add"];
ImagesAdd.DEFAULT_REGISTRY_URL = "https://index.docker.io/v1";
ImagesAdd.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    port: core_1.Flags.integer({ char: 'p', required: false, description: 'Recommended port number to assign, in the toybox template, to an Asset defined by this image.' }),
    sourceFile: core_1.Flags.string({ char: 'f', required: false, description: 'Path and filename of the image definition file, relative to the project root (eg: "./Dockerfile"). If omitted, the build will use an in-memory image definition auto-generated at build time.' }),
    registryUrl: core_1.Flags.string({ required: false, default: ImagesAdd.DEFAULT_REGISTRY_URL, char: 'r', description: '(Optional, defaults to Docker Hub) Address of the container registry to which the image will be published (without protocol prefix), eg: "yourimages.azurecr.io".' }),
    infoUrl: core_1.Flags.string({ required: false, char: 'i', description: '(Optional) Address on the registry website or portal of the human-readable web page for the image.' }),
    environment: core_1.Flags.string({ char: 'e', required: false, description: '(Optional) Declaration that this registry shall be the target when publishing to the given environment.' }),
    username: core_1.Flags.string({ char: 'u', required: false, description: '(Optional) Login credential for the given registry. WARNING: these credentials will be stored in the codiac config file in this project.' }),
    password: core_1.Flags.string({ char: 's', required: false, description: '(Optional) Password credential for the given registry. WARNING: these credentials will be stored in the codiac config file in this project.' }),
    buildParams: core_1.Flags.string({ char: 'b', required: false, multiple: true, description: 'Additional freeform arguments to apply to the Docker build command (as: arg=val, eg: -b "--size=12" -b "--color=blue").' }),
    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.' }),
};
ImagesAdd.args = {
    imageName: core_1.Args.string({ required: false, description: 'Image name including scope prefix, eg: "your-company/your-image".' })
};
ImagesAdd.examples = [
    { description: "Configure an image interactively.", command: "<%= config.bin %> <%= command.id %>" },
    { description: "Configure a named image.", command: "<%= config.bin %> <%= command.id %> your-company/your-image" },
    { description: "Renders the equivalent silent command without executing.", command: "<%= config.bin %> <%= command.id %> your-company/your-image --to-script" },
];
//# sourceMappingURL=add.js.map