// 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); }
};
import { inject, injectable } from 'tsyringe-neo';
import { patchInject } from './dependency-injection/container-helper.js';
import { SoloError } from './errors/solo-error.js';
import * as constants from './constants.js';
import fs from 'node:fs';
import { InjectTokens } from './dependency-injection/inject-tokens.js';
let CommandHandler = class CommandHandler {
    logger;
    configManager;
    accountManager;
    taskList;
    _configMaps = new Map();
    constructor(logger, configManager, accountManager, taskList) {
        this.logger = logger;
        this.configManager = configManager;
        this.accountManager = accountManager;
        this.taskList = taskList;
        this.logger = patchInject(logger, InjectTokens.SoloLogger, this.constructor.name);
        this.configManager = patchInject(configManager, InjectTokens.ConfigManager, this.constructor.name);
        this.accountManager = patchInject(accountManager, InjectTokens.AccountManager, this.constructor.name);
        this.taskList = patchInject(taskList, InjectTokens.TaskList, this.constructor.name);
    }
    async commandAction(argv, actionTasks, options, errorString, lease, commandName) {
        if (!commandName) {
            commandName = argv._.slice(0, 3).join(' ');
        }
        const tasks = this.taskList.newTaskList([...actionTasks], options, undefined, commandName);
        if (tasks.isRoot()) {
            try {
                await tasks.run();
            }
            catch (error) {
                throw new SoloError(`${errorString}: ${error.message}`, error);
            }
            finally {
                const promises = [];
                if (lease) {
                    promises.push(lease?.release());
                }
                promises.push(this.accountManager.close());
                await Promise.all(promises);
            }
        }
        else {
            this.taskList.registerCloseFunction(async () => {
                const promises = [];
                if (lease) {
                    promises.push(lease?.release());
                }
                promises.push(this.accountManager.close());
                await Promise.all(promises);
            });
        }
    }
    /**
     * Setup home directories
     * @param dirs a list of directories that need to be created in sequence
     */
    setupHomeDirectory(directories = [
        constants.SOLO_HOME_DIR,
        constants.SOLO_LOGS_DIR,
        constants.SOLO_CACHE_DIR,
        constants.SOLO_VALUES_DIR,
    ]) {
        const self = this;
        try {
            for (const directoryPath of directories) {
                if (!fs.existsSync(directoryPath)) {
                    fs.mkdirSync(directoryPath, { recursive: true });
                }
                self.logger.debug(`OK: setup directory: ${directoryPath}`);
            }
        }
        catch (error) {
            throw new SoloError(`failed to create directory: ${error.message}`, error);
        }
        return directories;
    }
    getUnusedConfigs(configName) {
        return this._configMaps.get(configName).getUnusedConfigs();
    }
};
CommandHandler = __decorate([
    injectable(),
    __param(0, inject(InjectTokens.SoloLogger)),
    __param(1, inject(InjectTokens.ConfigManager)),
    __param(2, inject(InjectTokens.AccountManager)),
    __param(3, inject(InjectTokens.TaskList)),
    __metadata("design:paramtypes", [Object, Function, Function, Object])
], CommandHandler);
export { CommandHandler };
//# sourceMappingURL=command-handler.js.map