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); }
};
/**
 * Copyright (C) 2024 Hedera Hashgraph, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the ""License"");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an ""AS IS"" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import { inject, injectable } from 'tsyringe-neo';
import { SoloError, MissingArgumentError } from './errors.js';
import { SoloLogger } from './logging.js';
import { Flags, Flags as flags } from '../commands/flags.js';
import * as paths from 'path';
import * as helpers from './helpers.js';
import { patchInject } from './container_helper.js';
import * as constants from '../core/constants.js';
/**
 * ConfigManager cache command flag values so that user doesn't need to enter the same values repeatedly.
 *
 * For example, 'namespace' is usually remains the same across commands once it is entered, and therefore user
 * doesn't need to enter it repeatedly. However, user should still be able to specify the flag explicitly for any command.
 */
let ConfigManager = class ConfigManager {
    logger;
    config;
    constructor(logger) {
        this.logger = logger;
        this.logger = patchInject(logger, SoloLogger, this.constructor.name);
        this.reset();
    }
    /** Reset config */
    reset() {
        this.config = {
            flags: {},
            version: helpers.packageVersion(),
            updatedAt: new Date().toISOString(),
        };
    }
    /**
     * Apply the command flags precedence
     *
     * It uses the below precedence for command flag values:
     *  1. User input of the command flag
     *  2. Default value of the command flag if the command is not 'init'.
     */
    applyPrecedence(argv, aliases) {
        for (const key of Object.keys(aliases)) {
            const flag = flags.allFlagsMap.get(key);
            if (flag) {
                // @ts-ignore
                if (argv[key] !== undefined) {
                    // argv takes precedence, nothing to do
                }
                else if (this.hasFlag(flag)) {
                    // @ts-ignore
                    argv[key] = this.getFlag(flag);
                }
                else {
                    // @ts-ignore
                    argv[key] = flag.definition.defaultValue;
                }
            }
        }
        return argv;
    }
    /** Update the config using the argv */
    update(argv = {}) {
        if (argv && Object.keys(argv).length > 0) {
            for (const flag of flags.allFlags) {
                if (argv[flag.name] !== undefined) {
                    let val = argv[flag.name];
                    switch (flag.definition.type) {
                        case 'string':
                            if (val && (flag.name === flags.chartDirectory.name || flag.name === flags.cacheDir.name)) {
                                this.logger.debug(`Resolving directory path for '${flag.name}': ${val}, to: ${paths.resolve(val)}, note: ~/ is not supported`);
                                val = paths.resolve(val);
                            }
                            this.config.flags[flag.name] = `${val}`; // force convert to string
                            break;
                        case 'number':
                            try {
                                if (flags.integerFlags.has(flag.name)) {
                                    this.config.flags[flag.name] = Number.parseInt(val);
                                }
                                else {
                                    this.config.flags[flag.name] = Number.parseFloat(val);
                                }
                            }
                            catch (e) {
                                throw new SoloError(`invalid number value '${val}': ${e.message}`, e);
                            }
                            break;
                        case 'boolean':
                            this.config.flags[flag.name] = val === true || val === 'true'; // use comparison to enforce boolean value
                            break;
                        case 'StorageType':
                            // @ts-ignore
                            if (!Object.values(constants.StorageType).includes(`${val}`)) {
                                throw new SoloError(`Invalid storage type value '${val}'`);
                            }
                            else {
                                this.config.flags[flag.name] = val;
                            }
                            break;
                        default:
                            throw new SoloError(`Unsupported field type for flag '${flag.name}': ${flag.definition.type}`);
                    }
                }
            }
            // store last command that was run
            if (argv._) {
                this.config.lastCommand = argv._;
            }
            this.config.updatedAt = new Date().toISOString();
            let flagMessage = '';
            for (const key of Object.keys(this.config.flags)) {
                if (this.config.flags[key]) {
                    flagMessage += `${key}=${this.config.flags[key]}, `;
                }
            }
            if (flagMessage) {
                this.logger.debug(`Updated config with flags: ${flagMessage}`);
            }
        }
    }
    /** Check if a flag value is set */
    hasFlag(flag) {
        return this.config.flags[flag.name] !== undefined;
    }
    /**
     * Return the value of the given flag
     * @returns value of the flag or undefined if flag value is not available
     */
    getFlag(flag) {
        if (this.config.flags[flag.name] !== undefined) {
            return this.config.flags[flag.name];
        }
        return undefined;
    }
    /** Set value for the flag */
    setFlag(flag, value) {
        if (!flag || !flag.name)
            throw new MissingArgumentError('flag must have a name');
        this.config.flags[flag.name] = value;
    }
    /** Get package version */
    getVersion() {
        return this.config.version;
    }
    /**
     * Run prompts for the given set of flags
     * @param task task object from listr2
     * @param flagList list of flag objects
     */
    async executePrompt(task, flagList = []) {
        for (const flag of flagList) {
            if (flag.definition.disablePrompt || flag.prompt === undefined) {
                continue;
            }
            if (this.getFlag(Flags.quiet)) {
                return;
            }
            const input = await flag.prompt(task, this.getFlag(flag));
            this.setFlag(flag, input);
        }
    }
};
ConfigManager = __decorate([
    injectable(),
    __param(0, inject(SoloLogger)),
    __metadata("design:paramtypes", [SoloLogger])
], ConfigManager);
export { ConfigManager };
//# sourceMappingURL=config_manager.js.map