"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BuildTypes = exports.PROMPT_ME_DESIGNATOR = void 0;
const tslib_1 = require("tslib");
require("reflect-metadata");
const core_1 = require("@oclif/core");
const command_base_1 = require("../cli-common/command-base");
const built_in_cli_user_input_1 = require("../cli-common/built-in-cli-user-input");
const build_configurator_1 = require("../uilogic/build-configurator");
const command_base_tenantless_1 = require("../command-base-tenantless");
const type_safety_utils_1 = require("../uilogic/type-safety-utils");
/** The value provided as input that indicates
 * a user's desire to be prompted with a list from which choose the value(s),
 * instead of entering them manually or taking a default. */
exports.PROMPT_ME_DESIGNATOR = "?";
var BuildTypes;
(function (BuildTypes) {
    BuildTypes["images"] = "images";
    BuildTypes["packages"] = "packages";
})(BuildTypes = exports.BuildTypes || (exports.BuildTypes = {}));
class Build extends command_base_tenantless_1.CommandBaseTenantless {
    run() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                this.bootstrap();
                let params = yield this.parse(Build);
                return this.exec.runWithDefaults(params, (args, flags) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                    return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                        try {
                            // const {args, flags} = this.parse(Build)  // this needs to happen first so help can override
                            // Commented out the dep install bc: This takes too much time to do here.
                            //   We need to check first to see fi theres any missing deps.
                            //   until then, leave it to dep:install for the the install-missing feature
                            // let npmOutput = await this._ops.dependencyInstallAll();
                            let buildDef;
                            // let projCfg = this.ioc.get(ProjectConfig);
                            console.log(JSON.stringify(flags));
                            // if (flags.as) {
                            //   if (projCfg.namedCalls && projCfg.namedCalls["build"]) {
                            //     // let namedCall: string|undefined;
                            //     // if (flags.as == PROMPT_ME_DESIGNATOR) {
                            //     //   let calls = _.keys(projCfg.namedCalls["build"]).sort();
                            //     //   namedCall = await this._ui.promptSelect("namedCall", "Select a build command:", ["1", "b", "other hand"]);
                            //     // } else {
                            //     //   namedCall = flags.as;
                            //     // }
                            //     // let memorized = projCfg.namedCalls!["build"][namedCall!];  // Why does TS need the assertion operator when we've already given an explicit type guard ?!?!
                            //     let memorized = projCfg.namedCalls!["build"][flags.as];
                            //     if (memorized) {
                            //       console.log(`Build def: ${JSON.stringify(memorized)}`);
                            //       if ((<any>memorized).args.buildDef) {
                            //         buildDef = [(<any>memorized).args.buildDef.split("|")];
                            //       }
                            //     } else {
                            //       throw new Error(`Cannot fire named call [${flags.as}]: that named call does not exist in the Codiac project file.  Use the flag --rememberAs to define it.`);
                            //     }
                            //   } else {
                            //     throw new Error(`Cannot fire named call [${flags.as}]: no named calls exist in the Codiac project file.  Use the flag --rememberAs to define one.`);
                            //   }
                            // } else
                            if (flags.buildDef) {
                                buildDef = flags.buildDef.split("|"); // Again with the assertion after an explicit type guard...!?!?!
                            }
                            else {
                                buildDef = [];
                            }
                            let buildConfig8r = new build_configurator_1.BuildConfigurator(this._ops, this._projCfg, new built_in_cli_user_input_1.BuiltInCliUserInput(), this._projectRoot, this.projCfgRepo, this.logger);
                            buildDef = yield buildConfig8r.getBuildDef(buildDef, flags.asDefault);
                            let versionBump;
                            if (flags.version || flags.major || flags.minor || flags.patch || flags.preid || flags.prerelease) {
                                versionBump = {
                                    fullName: flags.version,
                                    major: flags.major,
                                    minor: flags.minor,
                                    patch: flags.patch,
                                    preId: flags.preid,
                                    prerelease: flags.prerelease
                                };
                            }
                            let buildNumber = yield this._ops.build(versionBump, buildDef, flags.clear);
                            let skip = flags.skip ? type_safety_utils_1.TypeSafetyUtils.toEnum(BuildTypes, flags.skip) : undefined;
                            if (!skip || skip != BuildTypes.packages) {
                                // await this._ops.npmPackageBuild();  // this is dangerous if we reference a local pkg, cuz it could get checked in, which'll break the CICD build.
                            }
                            else {
                                this.logger.detail("Skipping packages build.");
                            }
                            if ((flags.image && flags.image.length > 0) || !skip || skip != BuildTypes.images) {
                                yield this._ops.buildProjectImages(buildNumber, versionBump, flags.frameworkVersion, flags.noCache, this._projUserCfg.identitySet, flags.buildTarget, flags.image);
                            }
                            else {
                                this.logger.detail("Skipping images build.");
                            }
                            this.logger.notice(this._styler.colorGood(`Build complete!`));
                            this._ui.userMessage(this._styler.colorGood(`Build complete!`));
                            resolve();
                        }
                        catch (err) {
                            this.handleError(err);
                            resolve(); //reject(err);
                        }
                    }));
                }));
            }
            catch (err) {
                // TODO: Consider this instead...
                // this.logger.error(`Error parsing arguments: ${err}`);
                // this.logger.debug(err.stack);
                // return new Promise<void>(async (res,rej) => res());
                return new Promise((res, rej) => tslib_1.__awaiter(this, void 0, void 0, function* () { return rej(new Error(`Error parsing arguments: ${err}`)); }));
            }
        });
    }
}
exports.default = Build;
Build.description = 'Builds the project and the docker container';
Build.flags = Object.assign(Object.assign({}, command_base_1.commandBase.globalFlags), { help: core_1.Flags.help({ char: 'h' }), frameworkVersion: core_1.Flags.string({ char: 'f', description: '(Future) Explicitly sets the version of the Toyhauler base image to use (default: latest).' }), noCache: core_1.Flags.boolean({ name: 'no-cache', char: 'n', description: 'Ignores the local Docker image cache, thereby forcing a fresh download of each image from its container registry layer in the build.' }), buildDef: core_1.Flags.string({ char: 'b', description: 'Replaces the default build command with the given process.  For a multi-command sequence, separate each with a Pipe (|) character.' }), asDefault: core_1.Flags.boolean({ char: 'd', dependsOn: ["buildDef"], description: 'Overwrites the default build command for the project with the buildDef argument' }), version: core_1.Flags.string({ description: 'Overwrites the full version for the build (using Major.Minor.Patch).' }), major: core_1.Flags.boolean({ char: 'M', description: 'Increments the version by one Major version number (using Major.Minor.Patch).' }), minor: core_1.Flags.boolean({ char: 'm', description: 'Increments the version by one Minor version number (using Major.Minor.Patch).' }), patch: core_1.Flags.boolean({ char: 'p', description: 'Increments the version by one Patch version number (using Major.Minor.Patch).' }), prerelease: core_1.Flags.boolean({ char: 'r', description: 'Increments the prerelease number (using Major.Minor.Patch-PreRelease).  NOTE:  Increments the Patch version number when appending.' }), preid: core_1.Flags.string({ char: 'i', description: 'Sets the prereleaseId and resets the prerelease number (or increments it if the same preid is already set) (using Major.Minor.Patch-PreId.PreRelease).  NOTE:  Increments the Patch version number when appending.' }), clear: core_1.Flags.boolean({ char: 'c', description: 'Completely deletes the output folder before building.' }), skip: core_1.Flags.string({ char: 's', options: [BuildTypes.images, BuildTypes.packages], description: '(optional) Prevents the building of any declared container images or packages.' }), image: core_1.Flags.string({ char: 'i', multiple: true, required: false, description: '(optional, defaults to all) Limits the list of images to build.  Value must match the name property of an image export defined in the codiac project file (codiac.json)' }), buildTarget: core_1.Flags.string({ char: 't', required: false, description: '(optional) Calls out the only stage to be built for images defined with multistage builds.' }) });
Build.args = {
// buildDef: Args.string({ description: 'Pipe (|) separated build cmds. Overrides the build command.' })
};
//# sourceMappingURL=build.js.map