"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const _ = require("lodash");
const command_base_exec_tenant_1 = require("../../../command-base-exec-tenant");
const k8s_utils_1 = require("../../../ops/k8s/k8s-utils");
const codiac_constants_1 = require("../../../codiac-constants");
const prettify_1 = require("../../../prettify");
class ClusterStackCapture extends command_base_exec_tenant_1.CommandBaseExecTenant {
    constructor() {
        super(...arguments);
        this.adminOnly = true;
    }
    bootstrap() {
        super.bootstrap();
        k8s_utils_1.K8sUtils.bootstrap(this.ioc, this);
    }
    captureArgs() {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { args, flags } = yield this.parse(ClusterStackCapture);
            let partial = {};
            if (args.name)
                partial.name = (_a = args.name) !== null && _a !== void 0 ? _a : codiac_constants_1.CliConstants.CLUSTER_STACK_NAME_DEFAULT;
            ;
            // ---------------------------------------------------------------
            // ---------------------------------------------------------------
            const takeDefaults = flags['take-defaults'];
            return [partial, takeDefaults];
        });
    }
    // /** Throws on invalid */
    // private validate(partial: Partial<IAuthRoleDef>): void {
    //   if (partial.name == undefined || _.isEmpty(partial.name)) throw new Error("Missing name");
    //   let rxName = /^[a-zA-Z][a-zA-Z0-9-]{2,50}$/;
    //   if (!rxName.test(partial.name)) throw new Error("Invalid name: must be 3- to 50-character string of alphanumerics and hyphens, starting with a letter.");
    // }
    buildCandidate_silently(partial) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let candidate = {
                name: partial.name
            };
            return candidate;
        });
    }
    buildCandidate_interactively(partial, takeDefaults) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            // partial.name = await this._ui.prompt("txtName", "Stack name: ", false, partial.name);
            return yield this.buildCandidate_silently(partial);
        });
    }
    buildCommandString(candidate, cmd) {
        cmd.push("--silent");
        if (candidate.name)
            cmd.push(candidate.name);
        return cmd;
    }
    executeTask(candidate) {
        var _a, _b, _c;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                this._ui.startSpinner("Capturing cluster stack...");
                const result = yield this.genRelayClient.Call.clusterStackCapture(candidate);
                this._ui.stopSpinner(result.success ? this._styler.colorGood("COMPLETE!") : this._styler.colorCritical("FAILED"));
                if (result.error)
                    throw result.error;
                if (result.output != undefined && !_.isEmpty(result.output)) {
                    const userOutput = (0, prettify_1.prettify)(result.output);
                    this._ui.userMessage("Successfully captured cluster stack ".concat("[", (_a = candidate.name) !== null && _a !== void 0 ? _a : codiac_constants_1.CliConstants.CLUSTER_STACK_NAME_DEFAULT, "]", result.message ? " " + result.message : ""));
                    this._ui.userMessage(userOutput);
                }
                else {
                    this._ui.userMessage("Unable to capture cluster stack ".concat("[", (_b = candidate.name) !== null && _b !== void 0 ? _b : codiac_constants_1.CliConstants.CLUSTER_STACK_NAME_DEFAULT, "]: ", (_c = result.message) !== null && _c !== void 0 ? _c : "(check logs for details)"));
                }
            }
            catch (err) {
                this.handleError(err);
            }
            finally {
                yield this.closeConnections();
                return;
            }
        });
    }
}
exports.default = ClusterStackCapture;
ClusterStackCapture.description = 'Fetches, creates, and configures each component of the built-in cluster stack.  This command only has to be run once for any given cluster stack.  NOTE: running this command will load the given cluster stack into your infrx enterprise and overwrite any existing assets that match by name and any matching settings at the enterprise level.  This command does not delete any existing settings.  NOTE:  This command DOES NOT directly modify any clusters.  It only loads asset and config records into Codiac for the infrx enterprise.';
ClusterStackCapture.aliases = [];
ClusterStackCapture.examples = [
    '<%= config.bin %> <%= command.id %> my-fav-cluster'
];
ClusterStackCapture.flags = {
    // "force-refresh": Flags.boolean({ char: 'f', description: 'Prevents a cache hit for the cluster connection and forces a new fetch from the remote cluster itself.' }),
    // TODO: Move these into the base class
    silent: core_1.Flags.boolean({ exclusive: ["echo", "to-script"], description: 'Non-Interactive mode; executes without any user interaction and fails on any missing or invalid arguments.' }),
    echo: core_1.Flags.boolean({ exclusive: ["to-script", "silent"], description: 'Echo interaction mode; renders the equivalent non-interactive cli command for future use before final execution.' }),
    "to-script": core_1.Flags.boolean({ exclusive: ["echo", "silent"], description: 'Toscript interaction mode; renders the equivalent non-interactive cli command WITHOUT any execution.' }),
    "take-defaults": core_1.Flags.boolean({ exclusive: ["silent"], description: "Setting this to true prevents prompting for confirmation on parameters that were passed in or were automatically set to default values (Irrelevant in --silent mode).  This behavior does NOT apply to scenarios that the command needs to override invalid user input; such cases will always prompt for confirmation.  eg: when no argument was provided for file or type, and only one exists, the system will render the autoselected file unless this flag is set." })
};
ClusterStackCapture.args = {
    name: core_1.Args.string({ required: false, description: '(optional, defaults to the Codiac builtin stack) Name of the cluster stack. Versions are selected later at tagging time and cluster install time.' }),
};
//# sourceMappingURL=capture.js.map