"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");
class ClusterAgentUninstall extends command_base_exec_tenant_1.CommandBaseExecTenant {
    constructor() {
        // static hidden = true;
        super(...arguments);
        this.adminOnly = true;
    }
    captureArgs() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { args, flags } = yield this.parse(ClusterAgentUninstall);
            let partial = {};
            if (args.cluster)
                partial.cluster = args.cluster;
            // ---------------------------------------------------------------
            // ---------------------------------------------------------------
            const takeDefaults = flags['take-defaults'];
            return [partial, takeDefaults];
        });
    }
    buildCandidate_silently(partial, rootMap) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (partial.cluster == undefined || _.isEmpty(partial.cluster))
                throw new Error("Must specify cluster.");
            const found = rootMap.clusters.find(c => c.name == partial.cluster);
            if (found == undefined)
                throw new Error(`No cluster found with name [${partial.cluster}].`);
            return { cluster: partial.cluster };
        });
    }
    buildCandidate_interactively(partial, takeDefaults, rootMap) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let clusters = rootMap.clusters.map(c => c);
            if (partial.cluster) {
                const found = clusters.find(c => c.name == partial.cluster);
                if (found == undefined) {
                    this._ui.userMessage(this._styler.colorWarning(`No cluster found with name [${partial.cluster}]; please select from the list below.`));
                    partial.cluster = undefined;
                }
            }
            let selected;
            if (clusters.length == 1 && takeDefaults) {
                selected = clusters[0];
            }
            else {
                selected = yield this.rootMapUtils.promptForCluster(clusters, partial.cluster);
            }
            partial.cluster = selected.name;
            return yield this.buildCandidate_silently(partial, rootMap);
        });
    }
    buildCommandString(candidate, cmd) {
        cmd.push("--silent");
        cmd.push(candidate.cluster);
        return cmd;
    }
    executeTask(candidate) {
        var _a, _b, _c;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                const result = yield this.watcher.triggerAndWatch((correlationId, socketId) => this.genRelayClient.Call.clusterEnvoyUninstall({
                    spec: { clusterName: candidate.cluster },
                    socketId: socketId,
                    correlationId: correlationId,
                }));
                if (result.error) {
                    const msg = `Error uninstalling Codiac agent from cluster [${candidate.cluster}]: ${(_a = result.message) !== null && _a !== void 0 ? _a : ""} ${(_b = result.error.message) !== null && _b !== void 0 ? _b : ""}`.trimEnd();
                    this.logger.error(msg, result.error);
                    this._ui.userMessage(`${this._styler.colorCritical("ERROR!")} ${msg}`);
                }
                else if (!result.success) {
                    const msg = `Codiac agent uninstall failed on cluster [${candidate.cluster}]: ${(_c = result.message) !== null && _c !== void 0 ? _c : ""}`.trimEnd();
                    this.logger.notice(msg, result);
                    this._ui.userMessage(`${this._styler.colorCritical("FAILED!")} ${msg}`);
                }
                else {
                    const msg = `${this._styler.colorGood("SUCCESS!")} Codiac agent uninstalled from cluster [${this._styler.hilite(candidate.cluster)}].`;
                    this.logger.notice(msg, result);
                    this._ui.userMessage(msg);
                }
            }
            catch (err) {
                throw err;
            }
            finally {
                return;
            }
        });
    }
}
exports.default = ClusterAgentUninstall;
ClusterAgentUninstall.description = 'Uninstalls the Codiac agent from the given cluster.';
ClusterAgentUninstall.aliases = ['cluster:envoy:uninstall'];
ClusterAgentUninstall.examples = [
    {
        description: 'Uninstall the Codiac agent from a cluster.',
        command: '<%= config.bin %> <%= command.id %> my-cluster',
    },
    {
        description: 'Non-interactive (scripted) invocation.',
        command: '<%= config.bin %> <%= command.id %> my-cluster --silent',
    },
    {
        description: 'Renders the equivalent silent command and then executes.',
        command: '<%= config.bin %> <%= command.id %> my-cluster --echo',
    },
    {
        description: 'Render the equivalent silent command without executing.',
        command: '<%= config.bin %> <%= command.id %> my-cluster --to-script',
    },
];
ClusterAgentUninstall.flags = {
    // 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: "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 where the command needs to override invalid user input; such cases will always prompt for confirmation." }),
};
ClusterAgentUninstall.args = {
    cluster: core_1.Args.string({ description: 'Name of the cluster in Codiac from which to uninstall the Codiac agent.  You can use `cod cluster list` to see available cluster names.' }),
};
//# sourceMappingURL=uninstall.js.map