"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_enterprise_1 = require("../../command-base-enterprise");
const prettify_1 = require("../../prettify");
const codiac_ops_common_1 = require("@codiac.io/codiac-ops-common");
class ImagesAdd extends command_base_enterprise_1.CommandBaseEnterprise {
    bootstrap() {
        if (ImagesAdd.isBootstrapped !== true) {
            this.requiresProjectScope = true; // <--- This command requires project scope.
            super.bootstrap();
        }
    }
    run() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            this.bootstrap();
            const { args, flags } = yield this.parse(ImagesAdd);
            try {
                // let target = new RegistryTarget(flags.environment||ImageExport.DEFAULT_ENVIRONMENT_NAME,
                //   flags.registryUrl || ImagesAdd.DEFAULT_REGISTRY_URL, flags.username, flags.password, flags.infoUrl);
                // This command requires project scope. 
                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 aas a project root.`);
                }
                // For now we are just forcing DockerCreds store
                let credsStore = this.ioc.getNamed(codiac_ops_common_1.INTERFACES_OPS.ICredentialsStore, codiac_ops_common_1.CredentialsStoreType.DockerDesktop);
                let 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 imageName = args.imageName;
                let sourceFile = flags.sourceFile;
                let port = flags.port;
                let buildParams = flags.buildParams;
                let confirmed = false;
                while (!confirmed) {
                    img = yield cfg8r.createImage(imageName, sourceFile, port, buildParams); // TODO: honor any input provided via flags
                    console.clear();
                    let msg = (0, prettify_1.prettify)(img);
                    this._ui.userMessage(msg);
                    this._ui.userMessage(`You are about to create ${img.name}. Continue?`);
                    confirmed = yield this._ui.promptConfirm("confirmCreate", `(hit 'N' to edit your input)`, false);
                }
                let 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.`);
                }
            }
            catch (err) {
                this.handleError(err);
            }
            finally {
                yield this.closeConnections();
                return;
            }
        });
    }
}
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"];
/** Registry defaults to Docker Hub */
ImagesAdd.DEFAULT_REGISTRY_URL = "https://index.docker.io/v1";
ImagesAdd.dependsOn = ["registryUrl", "port", "sourceFile", "username", "name"];
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.' }),
    // overwrite: Flags.custom({char: 'w', exclusive: ["readonly"], options: [PersistenceStrategy.never, PersistenceStrategy.always, PersistenceStrategy.asneeded], description: '(Optional, defaults to "never") Declares when the image build shall automatically create or overwrite the physical definitionFile with auto-generated content.  Only applicable when definitionFile is set.'}),
    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".  NOTE: This registry will be used by the "publish" command, whereas when running in "local" mode, images will instead be registered to the built-in image registry on the local machine.  NOTE:  This url shall define the default publishing target, for use when publishing for any environment, unless otherwise specified.' }),
    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 username/password credentials will be stored in the codiac config file in this project, and therefore configuring username and password in this manner is not recommended!' }),
    password: core_1.Flags.string({ char: 's', required: false, description: '(optional) Password credential for the given registry.  WARNING!! these username/password credentials will be stored in the codiac config file in this project, and therefore configuring username and password in this manner is not recommended!' }),
    silent: core_1.Flags.boolean({ char: 'y', dependsOn: ImagesAdd.dependsOn, required: false, description: `(Optional: defaults to false) Prevents confirmations of user-values that are remembered from prior runs. Requires: ${ImagesAdd.dependsOn}` }),
    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").' })
};
ImagesAdd.args = {
    imageName: core_1.Args.string({ required: false, description: 'image name including, scope prefix. eg:  "your-company/your-image"' })
};
//# sourceMappingURL=add.js.map