// SPDX-License-Identifier: Apache-2.0
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var NodeCommandHandlers_1;
import * as helpers from '../../core/helpers.js';
import * as NodeFlags from './flags.js';
import * as constants from '../../core/constants.js';
import { SoloError } from '../../core/errors/solo-error.js';
import { NodeSubcommandType } from '../../core/enumerations.js';
import { NodeHelper } from './helper.js';
import chalk from 'chalk';
import { inject, injectable } from 'tsyringe-neo';
import { patchInject } from '../../core/dependency-injection/container-helper.js';
import { CommandHandler } from '../../core/command-handler.js';
import { InjectTokens } from '../../core/dependency-injection/inject-tokens.js';
import { ComponentTypes } from '../../core/config/remote/enumerations/component-types.js';
import { DeploymentPhase } from '../../data/schema/model/remote/deployment-phase.js';
import { Templates } from '../../core/templates.js';
import { LedgerPhase } from '../../data/schema/model/remote/ledger-phase.js';
import { LocalConfigRuntimeState } from '../../business/runtime-state/config/local/local-config-runtime-state.js';
let NodeCommandHandlers = class NodeCommandHandlers extends CommandHandler {
    static { NodeCommandHandlers_1 = this; }
    leaseManager;
    localConfig;
    remoteConfig;
    tasks;
    configs;
    static SETUP_COMMAND = 'node setup';
    static START_COMMAND = 'node start';
    static KEYS_COMMAND = 'node keys';
    constructor(leaseManager, localConfig, remoteConfig, tasks, configs) {
        super();
        this.leaseManager = leaseManager;
        this.localConfig = localConfig;
        this.remoteConfig = remoteConfig;
        this.tasks = tasks;
        this.configs = configs;
        this.leaseManager = patchInject(leaseManager, InjectTokens.LockManager, this.constructor.name);
        this.configs = patchInject(configs, InjectTokens.NodeCommandConfigs, this.constructor.name);
        this.localConfig = patchInject(localConfig, InjectTokens.LocalConfigRuntimeState, this.constructor.name);
        this.remoteConfig = patchInject(remoteConfig, InjectTokens.RemoteConfigRuntimeState, this.constructor.name);
        this.tasks = patchInject(tasks, InjectTokens.NodeCommandTasks, this.constructor.name);
    }
    static ADD_CONTEXT_FILE = 'node-add.json';
    static DELETE_CONTEXT_FILE = 'node-delete.json';
    static UPDATE_CONTEXT_FILE = 'node-update.json';
    static UPGRADE_CONTEXT_FILE = 'node-upgrade.json';
    /** ******** Task Lists **********/
    deletePrepareTaskList(argv, lease) {
        return [
            this.tasks.initialize(argv, this.configs.deleteConfigBuilder.bind(this.configs), lease),
            this.validateSingleNodeState({ excludedPhases: [] }),
            this.tasks.identifyExistingNodes(),
            this.tasks.loadAdminKey(),
            this.tasks.prepareUpgradeZip(),
            this.tasks.checkExistingNodesStakedAmount(),
        ];
    }
    deleteSubmitTransactionsTaskList() {
        return [
            this.tasks.sendNodeDeleteTransaction(),
            this.tasks.sendPrepareUpgradeTransaction(),
            this.tasks.sendFreezeUpgradeTransaction(),
        ];
    }
    deleteExecuteTaskList() {
        return [
            this.tasks.checkAllNodesAreFrozen('existingNodeAliases'),
            this.tasks.stopNodes('existingNodeAliases'),
            this.tasks.downloadNodeGeneratedFiles(),
            this.tasks.prepareStagingDirectory('existingNodeAliases'),
            this.tasks.refreshNodeList(),
            this.tasks.copyNodeKeysToSecrets('refreshedConsensusNodes'),
            this.tasks.getNodeLogsAndConfigs(),
            this.tasks.updateChartWithConfigMap('Delete network node and update configMaps', NodeSubcommandType.DELETE),
            this.tasks.killNodes(),
            this.tasks.sleep('Give time for pods to come up after being killed', 20_000),
            this.tasks.checkNodePodsAreRunning(),
            this.tasks.populateServiceMap(),
            this.tasks.fetchPlatformSoftware('allNodeAliases'),
            this.tasks.setupNetworkNodes('allNodeAliases', false),
            this.tasks.startNodes('allNodeAliases'),
            this.tasks.enablePortForwarding(),
            this.tasks.checkAllNodesAreActive('allNodeAliases'),
            this.tasks.checkAllNodeProxiesAreActive(),
            this.tasks.triggerStakeWeightCalculate(NodeSubcommandType.DELETE),
            this.tasks.finalize(),
        ];
    }
    addPrepareTasks(argv, lease) {
        return [
            this.tasks.initialize(argv, this.configs.addConfigBuilder.bind(this.configs), lease),
            // TODO instead of validating the state we need to do a remote config add component, and we will need to manually
            //  the nodeAlias based on the next available node ID + 1
            // this.validateSingleNodeState({excludedPhases: []}),
            this.tasks.checkPVCsEnabled(),
            this.tasks.identifyExistingNodes(),
            this.tasks.determineNewNodeAccountNumber(),
            this.tasks.copyGrpcTlsCertificates(),
            this.tasks.generateGossipKey(),
            this.tasks.generateGrpcTlsKey(),
            this.tasks.loadSigningKeyCertificate(),
            this.tasks.computeMTLSCertificateHash(),
            this.tasks.prepareGossipEndpoints(),
            this.tasks.prepareGrpcServiceEndpoints(),
            this.tasks.prepareUpgradeZip(),
            this.tasks.checkExistingNodesStakedAmount(),
        ];
    }
    addSubmitTransactionsTasks() {
        return [
            this.tasks.sendNodeCreateTransaction(),
            this.tasks.sendPrepareUpgradeTransaction(),
            this.tasks.sendFreezeUpgradeTransaction(),
        ];
    }
    addExecuteTasks() {
        return [
            this.tasks.checkAllNodesAreFrozen('existingNodeAliases'),
            this.tasks.downloadNodeGeneratedFiles(),
            this.tasks.prepareStagingDirectory('allNodeAliases'),
            this.tasks.addNewConsensusNodeToRemoteConfig(),
            this.tasks.copyNodeKeysToSecrets(),
            this.tasks.getNodeLogsAndConfigs(),
            this.tasks.updateChartWithConfigMap('Deploy new network node', NodeSubcommandType.ADD),
            this.tasks.killNodes(),
            this.tasks.checkNodePodsAreRunning(),
            this.tasks.populateServiceMap(),
            this.tasks.fetchPlatformSoftware('allNodeAliases'),
            this.tasks.downloadLastState(),
            this.tasks.uploadStateToNewNode(),
            this.tasks.setupNetworkNodes('allNodeAliases', false),
            this.tasks.startNodes('allNodeAliases'),
            this.tasks.enablePortForwarding(),
            this.tasks.checkAllNodesAreActive('allNodeAliases'),
            this.tasks.checkAllNodeProxiesAreActive(),
            this.tasks.stakeNewNode(),
            this.tasks.triggerStakeWeightCalculate(NodeSubcommandType.ADD),
            this.tasks.finalize(),
        ];
    }
    updatePrepareTasks(argv, lease) {
        return [
            this.tasks.initialize(argv, this.configs.updateConfigBuilder.bind(this.configs), lease),
            this.validateSingleNodeState({ excludedPhases: [] }),
            this.tasks.identifyExistingNodes(),
            this.tasks.loadAdminKey(),
            this.tasks.prepareUpgradeZip(),
            this.tasks.checkExistingNodesStakedAmount(),
        ];
    }
    updateSubmitTransactionsTasks() {
        return [
            this.tasks.sendNodeUpdateTransaction(),
            this.tasks.sendPrepareUpgradeTransaction(),
            this.tasks.sendFreezeUpgradeTransaction(),
        ];
    }
    updateExecuteTasks() {
        return [
            this.tasks.checkAllNodesAreFrozen('existingNodeAliases'),
            this.tasks.downloadNodeGeneratedFiles(),
            this.tasks.prepareStagingDirectory('allNodeAliases'),
            this.tasks.copyNodeKeysToSecrets(),
            this.tasks.getNodeLogsAndConfigs(),
            this.tasks.updateChartWithConfigMap('Update chart to use new configMap due to account number change', NodeSubcommandType.UPDATE, context_ => !context_.config.newAccountNumber && !context_.config.debugNodeAlias),
            this.tasks.killNodesAndUpdateConfigMap(),
            this.tasks.checkNodePodsAreRunning(),
            this.tasks.fetchPlatformSoftware('allNodeAliases'),
            this.tasks.setupNetworkNodes('allNodeAliases', false),
            this.tasks.startNodes('allNodeAliases'),
            this.tasks.enablePortForwarding(),
            this.tasks.checkAllNodesAreActive('allNodeAliases'),
            this.tasks.checkAllNodeProxiesAreActive(),
            this.tasks.triggerStakeWeightCalculate(NodeSubcommandType.UPDATE),
            this.tasks.finalize(),
        ];
    }
    upgradePrepareTasks(argv, lease) {
        return [
            this.tasks.initialize(argv, this.configs.upgradeConfigBuilder.bind(this.configs), lease),
            this.validateAllNodePhases({ excludedPhases: [] }),
            this.tasks.identifyExistingNodes(),
            this.tasks.loadAdminKey(),
            this.tasks.prepareUpgradeZip(),
            this.tasks.checkExistingNodesStakedAmount(),
        ];
    }
    upgradeSubmitTransactionsTasks() {
        return [
            this.tasks.sendPrepareUpgradeTransaction(),
            this.tasks.sendFreezeUpgradeTransaction(),
        ];
    }
    upgradeExecuteTasks() {
        return [
            this.tasks.checkAllNodesAreFrozen('existingNodeAliases'),
            this.tasks.downloadNodeUpgradeFiles(),
            this.tasks.getNodeLogsAndConfigs(),
            this.tasks.fetchPlatformSoftware('nodeAliases'),
            this.tasks.startNodes('allNodeAliases'),
            this.tasks.enablePortForwarding(),
            this.tasks.checkAllNodesAreActive('allNodeAliases'),
            this.tasks.checkAllNodeProxiesAreActive(),
            this.tasks.finalize(),
        ];
    }
    /** ******** Handlers **********/
    async prepareUpgrade(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.PREPARE_UPGRADE_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.prepareUpgradeConfigBuilder.bind(this.configs), leaseWrapper.lease),
            this.tasks.identifyExistingNodes(),
            this.tasks.prepareStagingDirectory('existingNodeAliases'),
            this.tasks.prepareUpgradeZip(),
            this.tasks.sendPrepareUpgradeTransaction(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in preparing node upgrade', leaseWrapper.lease);
        return true;
    }
    async freezeUpgrade(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.PREPARE_UPGRADE_FLAGS);
        await this.commandAction(argv, [
            this.tasks.initialize(argv, this.configs.prepareUpgradeConfigBuilder.bind(this.configs), null),
            this.tasks.identifyExistingNodes(),
            this.tasks.prepareUpgradeZip(),
            this.tasks.sendFreezeUpgradeTransaction(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in executing node freeze upgrade', null);
        return true;
    }
    async downloadGeneratedFiles(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.DEFAULT_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.downloadGeneratedFilesConfigBuilder.bind(this.configs), leaseWrapper.lease),
            this.tasks.identifyExistingNodes(),
            this.tasks.downloadNodeGeneratedFiles(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in downloading generated files', leaseWrapper.lease);
        return true;
    }
    async update(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.UPDATE_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            ...this.updatePrepareTasks(argv, leaseWrapper.lease),
            ...this.updateSubmitTransactionsTasks(),
            ...this.updateExecuteTasks(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in updating nodes', leaseWrapper.lease);
        return true;
    }
    async updatePrepare(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.UPDATE_PREPARE_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            ...this.updatePrepareTasks(argv, leaseWrapper.lease),
            this.tasks.saveContextData(argv, NodeCommandHandlers_1.UPDATE_CONTEXT_FILE, NodeHelper.updateSaveContextParser),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in preparing node update', leaseWrapper.lease);
        return true;
    }
    async updateSubmitTransactions(argv) {
        const leaseWrapper = { lease: null };
        argv = helpers.addFlagsToArgv(argv, NodeFlags.UPDATE_SUBMIT_TRANSACTIONS_FLAGS);
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.updateConfigBuilder.bind(this.configs), leaseWrapper.lease),
            this.tasks.loadContextData(argv, NodeCommandHandlers_1.UPDATE_CONTEXT_FILE, NodeHelper.updateLoadContextParser),
            ...this.updateSubmitTransactionsTasks(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in submitting transactions for node update', leaseWrapper.lease);
        return true;
    }
    async updateExecute(argv) {
        const leaseWrapper = { lease: null };
        argv = helpers.addFlagsToArgv(argv, NodeFlags.UPDATE_EXECUTE_FLAGS);
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.updateConfigBuilder.bind(this.configs), leaseWrapper.lease, false),
            this.tasks.loadContextData(argv, NodeCommandHandlers_1.UPDATE_CONTEXT_FILE, NodeHelper.updateLoadContextParser),
            ...this.updateExecuteTasks(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in executing network upgrade', leaseWrapper.lease);
        return true;
    }
    async upgradePrepare(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.UPGRADE_PREPARE_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            ...this.upgradePrepareTasks(argv, leaseWrapper.lease),
            this.tasks.saveContextData(argv, NodeCommandHandlers_1.UPGRADE_CONTEXT_FILE, NodeHelper.upgradeSaveContextParser),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in preparing node upgrade', leaseWrapper.lease);
        return true;
    }
    async upgradeSubmitTransactions(argv) {
        const leaseWrapper = { lease: null };
        argv = helpers.addFlagsToArgv(argv, NodeFlags.UPGRADE_SUBMIT_TRANSACTIONS_FLAGS);
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.upgradeConfigBuilder.bind(this.configs), leaseWrapper.lease),
            this.tasks.loadContextData(argv, NodeCommandHandlers_1.UPGRADE_CONTEXT_FILE, NodeHelper.upgradeLoadContextParser),
            ...this.upgradeSubmitTransactionsTasks(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in submitting transactions for node upgrade', leaseWrapper.lease);
        return true;
    }
    async upgradeExecute(argv) {
        const leaseWrapper = { lease: null };
        argv = helpers.addFlagsToArgv(argv, NodeFlags.UPGRADE_FLAGS);
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.upgradeConfigBuilder.bind(this.configs), leaseWrapper.lease, false),
            this.tasks.loadContextData(argv, NodeCommandHandlers_1.UPGRADE_CONTEXT_FILE, NodeHelper.upgradeLoadContextParser),
            ...this.upgradeExecuteTasks(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in executing network upgrade', leaseWrapper.lease);
        return true;
    }
    async upgrade(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.UPGRADE_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            ...this.upgradePrepareTasks(argv, leaseWrapper.lease),
            ...this.upgradeSubmitTransactionsTasks(),
            ...this.upgradeExecuteTasks(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in upgrade network', leaseWrapper.lease);
        return true;
    }
    async delete(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.DELETE_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            ...this.deletePrepareTaskList(argv, leaseWrapper.lease),
            ...this.deleteSubmitTransactionsTaskList(),
            ...this.deleteExecuteTaskList(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in deleting nodes', leaseWrapper.lease);
        return true;
    }
    async deletePrepare(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.DELETE_PREPARE_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            ...this.deletePrepareTaskList(argv, leaseWrapper.lease),
            this.tasks.saveContextData(argv, NodeCommandHandlers_1.DELETE_CONTEXT_FILE, NodeHelper.deleteSaveContextParser),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in preparing to delete a node', leaseWrapper.lease);
        return true;
    }
    async deleteSubmitTransactions(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.DELETE_SUBMIT_TRANSACTIONS_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.deleteConfigBuilder.bind(this.configs), leaseWrapper.lease),
            this.tasks.loadContextData(argv, NodeCommandHandlers_1.DELETE_CONTEXT_FILE, NodeHelper.deleteLoadContextParser),
            ...this.deleteSubmitTransactionsTaskList(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in deleting a node', leaseWrapper.lease);
        return true;
    }
    async deleteExecute(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.DELETE_EXECUTE_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.deleteConfigBuilder.bind(this.configs), leaseWrapper.lease, false),
            this.tasks.loadContextData(argv, NodeCommandHandlers_1.DELETE_CONTEXT_FILE, NodeHelper.deleteLoadContextParser),
            ...this.deleteExecuteTaskList(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in deleting a node', leaseWrapper.lease);
        return true;
    }
    async add(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.ADD_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            ...this.addPrepareTasks(argv, leaseWrapper.lease),
            ...this.addSubmitTransactionsTasks(),
            ...this.addExecuteTasks(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in adding node', leaseWrapper.lease);
        return true;
    }
    async addPrepare(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.ADD_PREPARE_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            ...this.addPrepareTasks(argv, leaseWrapper.lease),
            this.tasks.saveContextData(argv, NodeCommandHandlers_1.ADD_CONTEXT_FILE, helpers.addSaveContextParser),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in preparing node', leaseWrapper.lease);
        return true;
    }
    async addSubmitTransactions(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.ADD_SUBMIT_TRANSACTIONS_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.addConfigBuilder.bind(this.configs), leaseWrapper.lease),
            this.tasks.loadContextData(argv, NodeCommandHandlers_1.ADD_CONTEXT_FILE, helpers.addLoadContextParser),
            ...this.addSubmitTransactionsTasks(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, '`Error in submitting transactions to node', leaseWrapper.lease);
        return true;
    }
    async addExecute(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.ADD_EXECUTE_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.addConfigBuilder.bind(this.configs), leaseWrapper.lease, false),
            this.tasks.identifyExistingNodes(),
            this.tasks.loadContextData(argv, NodeCommandHandlers_1.ADD_CONTEXT_FILE, helpers.addLoadContextParser),
            ...this.addExecuteTasks(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in adding node', leaseWrapper.lease);
        return true;
    }
    async logs(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.LOGS_FLAGS);
        await this.commandAction(argv, [
            this.tasks.initialize(argv, this.configs.logsConfigBuilder.bind(this.configs), null),
            this.tasks.getNodeLogsAndConfigs(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in downloading log from nodes', null);
        return true;
    }
    async states(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.STATES_FLAGS);
        await this.commandAction(argv, [
            this.tasks.initialize(argv, this.configs.statesConfigBuilder.bind(this.configs), null),
            this.tasks.getNodeStateFiles(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in downloading states from nodes', null);
        return true;
    }
    // TODO this is broken, since genesis reconnects is no longer supported in 0.59+
    // TODO this is not in the test harness
    async refresh(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.REFRESH_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.refreshConfigBuilder.bind(this.configs), leaseWrapper.lease),
            this.validateAllNodePhases({
                acceptedPhases: [DeploymentPhase.STARTED, DeploymentPhase.CONFIGURED, DeploymentPhase.DEPLOYED],
            }),
            this.tasks.identifyNetworkPods(),
            this.tasks.dumpNetworkNodesSaveState(),
            this.tasks.fetchPlatformSoftware('nodeAliases'),
            this.tasks.setupNetworkNodes('nodeAliases', true),
            this.tasks.startNodes('nodeAliases'),
            this.tasks.checkAllNodesAreActive('nodeAliases'),
            this.tasks.checkNodeProxiesAreActive(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in refreshing nodes', leaseWrapper.lease);
        return true;
    }
    async keys(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.KEYS_FLAGS);
        await this.commandAction(argv, [
            this.tasks.initialize(argv, this.configs.keysConfigBuilder.bind(this.configs), null),
            this.tasks.generateGossipKeys(),
            this.tasks.generateGrpcTlsKeys(),
            this.tasks.finalize(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error generating keys', null, NodeCommandHandlers_1.KEYS_COMMAND);
        return true;
    }
    async stop(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.STOP_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.stopConfigBuilder.bind(this.configs), leaseWrapper.lease),
            this.validateAllNodePhases({
                acceptedPhases: [DeploymentPhase.STARTED, DeploymentPhase.CONFIGURED],
            }),
            this.tasks.identifyNetworkPods(1),
            this.tasks.stopNodes('nodeAliases'),
            this.changeAllNodePhases(DeploymentPhase.STARTED),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error stopping node', leaseWrapper.lease);
        return true;
    }
    async start(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.START_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.startConfigBuilder.bind(this.configs), leaseWrapper.lease),
            this.validateAllNodePhases({ acceptedPhases: [DeploymentPhase.CONFIGURED] }),
            this.tasks.identifyExistingNodes(),
            this.tasks.uploadStateFiles(context_ => context_.config.stateFile.length === 0),
            this.tasks.startNodes('nodeAliases'),
            this.tasks.enablePortForwarding(true),
            this.tasks.checkAllNodesAreActive('nodeAliases'),
            this.tasks.checkNodeProxiesAreActive(),
            this.changeAllNodePhases(DeploymentPhase.STARTED, LedgerPhase.INITIALIZED),
            this.tasks.addNodeStakes(),
            this.tasks.setGrpcWebEndpoint(),
            // TODO only show this if we are not running in quick-start mode
            // this.tasks.showUserMessages(),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error starting node', leaseWrapper.lease, NodeCommandHandlers_1.START_COMMAND);
        return true;
    }
    async setup(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.SETUP_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.setupConfigBuilder.bind(this.configs), leaseWrapper.lease),
            this.validateAllNodePhases({
                acceptedPhases: [DeploymentPhase.DEPLOYED],
            }),
            this.tasks.identifyNetworkPods(),
            this.tasks.fetchPlatformSoftware('nodeAliases'),
            this.tasks.setupNetworkNodes('nodeAliases', true),
            this.tasks.setupNetworkNodeFolders(),
            this.changeAllNodePhases(DeploymentPhase.CONFIGURED),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error in setting up nodes', leaseWrapper.lease, NodeCommandHandlers_1.SETUP_COMMAND);
        return true;
    }
    async freeze(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.FREEZE_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.freezeConfigBuilder.bind(this.configs), leaseWrapper.lease),
            this.tasks.identifyExistingNodes(),
            this.tasks.sendFreezeTransaction(),
            this.tasks.checkAllNodesAreFrozen('existingNodeAliases'),
            this.tasks.stopNodes('existingNodeAliases'),
            this.changeAllNodePhases(DeploymentPhase.FROZEN),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error freezing node', leaseWrapper.lease);
        return true;
    }
    async restart(argv) {
        argv = helpers.addFlagsToArgv(argv, NodeFlags.RESTART_FLAGS);
        const leaseWrapper = { lease: null };
        await this.commandAction(argv, [
            this.tasks.loadConfiguration(argv, leaseWrapper, this.leaseManager),
            this.tasks.initialize(argv, this.configs.restartConfigBuilder.bind(this.configs), leaseWrapper.lease),
            this.tasks.identifyExistingNodes(),
            this.tasks.startNodes('existingNodeAliases'),
            this.tasks.enablePortForwarding(),
            this.tasks.checkAllNodesAreActive('existingNodeAliases'),
            this.tasks.checkNodeProxiesAreActive(),
            this.changeAllNodePhases(DeploymentPhase.STARTED),
        ], {
            concurrent: false,
            rendererOptions: constants.LISTR_DEFAULT_RENDERER_OPTION,
        }, 'Error restarting node', leaseWrapper.lease);
        return true;
    }
    /**
     * Changes the state from all consensus nodes components in remote config.
     *
     * @param phase - to which to change the consensus node component
     * @param ledgerPhase
     */
    changeAllNodePhases(phase, ledgerPhase = undefined) {
        return {
            title: `Change node state to ${phase} in remote config`,
            skip: () => !this.remoteConfig.isLoaded(),
            task: async (context_) => {
                for (const consensusNode of context_.config.consensusNodes) {
                    const nodeId = Templates.nodeIdFromNodeAlias(consensusNode.name);
                    this.remoteConfig.configuration.components.changeNodePhase(nodeId, phase);
                }
                if (ledgerPhase) {
                    this.remoteConfig.configuration.state.ledgerPhase = ledgerPhase;
                }
                await this.remoteConfig.persist();
            },
        };
    }
    /**
     * Creates tasks to validate that each node state is either one of the accepted states or not one of the excluded.
     *
     * @param acceptedPhases - the state at which the nodes can be, not matching any of the states throws an error
     * @param excludedPhases - the state at which the nodes can't be, matching any of the states throws an error
     */
    validateAllNodePhases({ acceptedPhases, excludedPhases, }) {
        return {
            title: 'Validate nodes states',
            skip: () => !this.remoteConfig.isLoaded(),
            task: (context_, task) => {
                const nodeAliases = context_.config.nodeAliases;
                const subTasks = nodeAliases.map(nodeAlias => ({
                    title: `Validating state for node ${nodeAlias}`,
                    task: (_, task) => {
                        const state = this.validateNodeState(nodeAlias, this.remoteConfig.configuration.components, acceptedPhases, excludedPhases);
                        task.title += ` - ${chalk.green('valid state')}: ${chalk.cyan(state)}`;
                    },
                }));
                return task.newListr(subTasks, {
                    concurrent: false,
                    rendererOptions: { collapseSubtasks: false },
                });
            },
        };
    }
    /**
     * Creates tasks to validate that specific node state is either one of the accepted states or not one of the excluded.
     *
     * @param acceptedPhases - the state at which the node can be, not matching any of the states throws an error
     * @param excludedPhases - the state at which the node can't be, matching any of the states throws an error
     */
    validateSingleNodeState({ acceptedPhases, excludedPhases, }) {
        return {
            title: 'Validate nodes state',
            skip: () => !this.remoteConfig.isLoaded(),
            task: (context_, task) => {
                const nodeAlias = context_.config.nodeAlias;
                task.title += ` ${nodeAlias}`;
                // TODO: Disabled for now until the node's state mapping is completed
                // const components = this.remoteConfig.components;
                // const state = this.validateNodeState(nodeAlias, components, acceptedPhases, excludedPhases);
                // task.title += ` - ${chalk.green('valid state')}: ${chalk.cyan(state)}`;
            },
        };
    }
    /**
     * @param nodeAlias - the alias of the node whose state to validate
     * @param components - the component data wrapper
     * @param acceptedPhases - the state at which the node can be, not matching any of the states throws an error
     * @param excludedPhases - the state at which the node can't be, matching any of the states throws an error
     */
    validateNodeState(nodeAlias, components, acceptedPhases, excludedPhases) {
        let nodeComponent;
        try {
            nodeComponent = components.getComponent(ComponentTypes.ConsensusNode, Templates.nodeIdFromNodeAlias(nodeAlias));
        }
        catch {
            throw new SoloError(`${nodeAlias} not found in remote config`);
        }
        // TODO: Enable once the states have been mapped
        // if (acceptedPhases && !acceptedPhases.includes(nodeComponent.state)) {
        //   const errorMessageData =
        //     `accepted states: ${acceptedPhases.join(', ')}, ` + `current state: ${nodeComponent.state}`;
        //
        //   throw new SoloError(`${nodeAlias} has invalid state - ` + errorMessageData);
        // }
        //
        // if (excludedPhases && excludedPhases.includes(nodeComponent.state)) {
        //   const errorMessageData =
        //     `excluded states: ${excludedPhases.join(', ')}, ` + `current state: ${nodeComponent.state}`;
        //
        //   throw new SoloError(`${nodeAlias} has invalid state - ` + errorMessageData);
        // }
        return nodeComponent.metadata.phase;
    }
};
NodeCommandHandlers = NodeCommandHandlers_1 = __decorate([
    injectable(),
    __param(0, inject(InjectTokens.LockManager)),
    __param(1, inject(InjectTokens.LocalConfigRuntimeState)),
    __param(2, inject(InjectTokens.RemoteConfigRuntimeState)),
    __param(3, inject(InjectTokens.NodeCommandTasks)),
    __param(4, inject(InjectTokens.NodeCommandConfigs)),
    __metadata("design:paramtypes", [Function, LocalConfigRuntimeState, Object, Function, Function])
], NodeCommandHandlers);
export { NodeCommandHandlers };
//# sourceMappingURL=handlers.js.map