// 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 { SoloError } from '../core/errors/solo-error.js';
import { ShellRunner } from '../core/shell-runner.js';
import * as constants from '../core/constants.js';
import fs from 'node:fs';
import { Flags } from './flags.js';
import { PathEx } from '../business/utils/path-ex.js';
import { inject } from 'tsyringe-neo';
import { patchInject } from '../core/dependency-injection/container-helper.js';
import { InjectTokens } from '../core/dependency-injection/inject-tokens.js';
let BaseCommand = class BaseCommand extends ShellRunner {
    helm;
    k8Factory;
    chartManager;
    configManager;
    depManager;
    leaseManager;
    localConfig;
    remoteConfig;
    taskList;
    constructor(helm, k8Factory, chartManager, configManager, depManager, leaseManager, localConfig, remoteConfig, taskList) {
        super();
        this.helm = helm;
        this.k8Factory = k8Factory;
        this.chartManager = chartManager;
        this.configManager = configManager;
        this.depManager = depManager;
        this.leaseManager = leaseManager;
        this.localConfig = localConfig;
        this.remoteConfig = remoteConfig;
        this.taskList = taskList;
        this.helm = patchInject(helm, InjectTokens.Helm, this.constructor.name);
        this.k8Factory = patchInject(k8Factory, InjectTokens.K8Factory, this.constructor.name);
        this.chartManager = patchInject(chartManager, InjectTokens.ChartManager, this.constructor.name);
        this.configManager = patchInject(configManager, InjectTokens.ConfigManager, this.constructor.name);
        this.depManager = patchInject(depManager, InjectTokens.DependencyManager, this.constructor.name);
        this.leaseManager = patchInject(leaseManager, InjectTokens.LockManager, this.constructor.name);
        this.localConfig = patchInject(localConfig, InjectTokens.LocalConfigRuntimeState, this.constructor.name);
        this.remoteConfig = patchInject(remoteConfig, InjectTokens.RemoteConfigRuntimeState, this.constructor.name);
        this.taskList = patchInject(taskList, InjectTokens.TaskList, this.constructor.name);
    }
    /**
     * Prepare the values files map for each cluster
     *
     * Order of precedence:
     * 1. Chart's default values file (if chartDirectory is set)
     * 2. Profile values file
     * 3. User's values file
     * @param clusterReferences
     * @param valuesFileInput - the values file input string
     * @param chartDirectory - the chart directory
     * @param profileValuesFile - mapping of clusterRef to the profile values file full path
     */
    static prepareValuesFilesMapMultipleCluster(clusterReferences, chartDirectory, profileValuesFile, valuesFileInput) {
        // initialize the map with an empty array for each cluster-ref
        const valuesFiles = { [Flags.KEY_COMMON]: '' };
        for (const [clusterReference] of clusterReferences) {
            valuesFiles[clusterReference] = '';
        }
        // add the chart's default values file for each cluster-ref if chartDirectory is set
        // this should be the first in the list of values files as it will be overridden by user's input
        if (chartDirectory) {
            const chartValuesFile = PathEx.join(chartDirectory, 'solo-deployment', 'values.yaml');
            for (const clusterReference in valuesFiles) {
                valuesFiles[clusterReference] += ` --values ${chartValuesFile}`;
            }
        }
        if (profileValuesFile) {
            for (const [clusterReference, file] of Object.entries(profileValuesFile)) {
                const valuesArgument = ` --values ${file}`;
                if (clusterReference === Flags.KEY_COMMON) {
                    for (const clusterReference_ of Object.keys(valuesFiles)) {
                        valuesFiles[clusterReference_] += valuesArgument;
                    }
                }
                else {
                    valuesFiles[clusterReference] += valuesArgument;
                }
            }
        }
        if (valuesFileInput) {
            const parsed = Flags.parseValuesFilesInput(valuesFileInput);
            for (const [clusterReference, files] of Object.entries(parsed)) {
                let vf = '';
                for (const file of files) {
                    vf += ` --values ${file}`;
                }
                if (clusterReference === Flags.KEY_COMMON) {
                    for (const [clusterReference_] of Object.entries(valuesFiles)) {
                        valuesFiles[clusterReference_] += vf;
                    }
                }
                else {
                    valuesFiles[clusterReference] += vf;
                }
            }
        }
        if (Object.keys(valuesFiles).length > 1) {
            // delete the common key if there is another cluster to use
            delete valuesFiles[Flags.KEY_COMMON];
        }
        return valuesFiles;
    }
    /**
     * Prepare the values files map for each cluster
     *
     * Order of precedence:
     * 1. Chart's default values file (if chartDirectory is set)
     * 2. Profile values file
     * 3. User's values file
     * @param clusterReferences
     * @param valuesFileInput - the values file input string
     * @param chartDirectory - the chart directory
     * @param profileValuesFile - the profile values file full path
     */
    static prepareValuesFilesMap(clusterReferences, chartDirectory, profileValuesFile, valuesFileInput) {
        // initialize the map with an empty array for each cluster-ref
        const valuesFiles = {
            [Flags.KEY_COMMON]: '',
        };
        for (const [clusterReference] of clusterReferences) {
            valuesFiles[clusterReference] = '';
        }
        // add the chart's default values file for each cluster-ref if chartDirectory is set
        // this should be the first in the list of values files as it will be overridden by user's input
        if (chartDirectory) {
            const chartValuesFile = PathEx.join(chartDirectory, 'solo-deployment', 'values.yaml');
            for (const clusterReference in valuesFiles) {
                valuesFiles[clusterReference] += ` --values ${chartValuesFile}`;
            }
        }
        if (profileValuesFile) {
            const parsed = Flags.parseValuesFilesInput(profileValuesFile);
            for (const [clusterReference, files] of Object.entries(parsed)) {
                let vf = '';
                for (const file of files) {
                    vf += ` --values ${file}`;
                }
                if (clusterReference === Flags.KEY_COMMON) {
                    for (const [cf] of Object.entries(valuesFiles)) {
                        valuesFiles[cf] += vf;
                    }
                }
                else {
                    valuesFiles[clusterReference] += vf;
                }
            }
        }
        if (valuesFileInput) {
            const parsed = Flags.parseValuesFilesInput(valuesFileInput);
            for (const [clusterReference, files] of Object.entries(parsed)) {
                let vf = '';
                for (const file of files) {
                    vf += ` --values ${file}`;
                }
                if (clusterReference === Flags.KEY_COMMON) {
                    for (const [clusterReference_] of Object.entries(valuesFiles)) {
                        valuesFiles[clusterReference_] += vf;
                    }
                }
                else {
                    valuesFiles[clusterReference] += vf;
                }
            }
        }
        if (Object.keys(valuesFiles).length > 1) {
            // delete the common key if there is another cluster to use
            delete valuesFiles[Flags.KEY_COMMON];
        }
        return valuesFiles;
    }
    /**
     * Setup home directories
     * @param directories
     */
    setupHomeDirectory(directories = []) {
        if (!directories || directories?.length === 0) {
            directories = [
                constants.SOLO_HOME_DIR,
                constants.SOLO_LOGS_DIR,
                this.configManager.getFlag(Flags.cacheDir) || 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;
    }
    setupHomeDirectoryTask() {
        return {
            tile: 'Setup home directory',
            task: async () => {
                this.setupHomeDirectory();
            },
        };
    }
};
BaseCommand = __decorate([
    __param(0, inject(InjectTokens.Helm)),
    __param(1, inject(InjectTokens.K8Factory)),
    __param(2, inject(InjectTokens.ChartManager)),
    __param(3, inject(InjectTokens.ConfigManager)),
    __param(4, inject(InjectTokens.DependencyManager)),
    __param(5, inject(InjectTokens.LockManager)),
    __param(6, inject(InjectTokens.LocalConfigRuntimeState)),
    __param(7, inject(InjectTokens.RemoteConfigRuntimeState)),
    __param(8, inject(InjectTokens.TaskList)),
    __metadata("design:paramtypes", [Object, Object, Function, Function, Function, Function, Function, Object, Object])
], BaseCommand);
export { BaseCommand };
//# sourceMappingURL=base.js.map