// 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 { Flags as flags } from '../../commands/flags.js';
import { IntervalLock } from './interval-lock.js';
import { LockHolder } from './lock-holder.js';
import { inject, injectable } from 'tsyringe-neo';
import { patchInject } from '../dependency-injection/container-helper.js';
import { InjectTokens } from '../dependency-injection/inject-tokens.js';
import { LockAcquisitionError } from './lock-acquisition-error.js';
/**
 * Manages the acquisition and renewal of locks.
 */
let LockManager = class LockManager {
    _renewalService;
    _logger;
    k8Factory;
    configManager;
    remoteConfigRuntimeState;
    /**
     * Creates a new lock manager.
     *
     * @param _renewalService - the lock renewal service.
     * @param _logger - the logger.
     * @param k8Factory - the Kubernetes client.
     * @param configManager - the configuration manager.
     * @param remoteConfigRuntimeState
     */
    constructor(_renewalService, _logger, k8Factory, configManager, remoteConfigRuntimeState) {
        this._renewalService = _renewalService;
        this._logger = _logger;
        this.k8Factory = k8Factory;
        this.configManager = configManager;
        this.remoteConfigRuntimeState = remoteConfigRuntimeState;
        this._renewalService = patchInject(_renewalService, InjectTokens.LockRenewalService, this.constructor.name);
        this._logger = patchInject(_logger, InjectTokens.SoloLogger, this.constructor.name);
        this.k8Factory = patchInject(k8Factory, InjectTokens.K8Factory, this.constructor.name);
        this.configManager = patchInject(configManager, InjectTokens.ConfigManager, this.constructor.name);
        this.remoteConfigRuntimeState = patchInject(remoteConfigRuntimeState, InjectTokens.RemoteConfigRuntimeState, this.constructor.name);
    }
    /**
     * Creates a new lease. This lease is not acquired until the `acquire` method is called.
     *
     * @returns a new lease instance.
     */
    async create() {
        let namespace;
        try {
            namespace = this.remoteConfigRuntimeState.getNamespace();
        }
        catch {
            // If the namespace is not set in the remote config, we will use the current namespace.
        }
        if (!namespace) {
            namespace = await this.currentNamespace();
        }
        return new IntervalLock(this.k8Factory, this._renewalService, LockHolder.default(), namespace);
    }
    /**
     * Retrieves the renewal service implementation.
     *
     * @returns the lease renewal service.
     */
    get renewalService() {
        return this._renewalService;
    }
    /**
     * Retrieves the logger instance.
     *
     * @returns the logger.
     */
    get logger() {
        return this._logger;
    }
    /**
     * Retrieves the user or configuration supplied namespace to use for lease acquisition.
     *
     * @returns the namespace to use for lease acquisition or null if no namespace is specified.
     * @throws LockAcquisitionError if the namespace does not exist and cannot be created.
     */
    async currentNamespace() {
        const deploymentNamespace = this.configManager.getFlag(flags.namespace);
        const clusterSetupNamespace = this.configManager.getFlag(flags.clusterSetupNamespace);
        if (!deploymentNamespace && !clusterSetupNamespace) {
            return null;
        }
        const namespace = deploymentNamespace ? deploymentNamespace : clusterSetupNamespace;
        if (!(await this.k8Factory.default().namespaces().has(namespace))) {
            await this.k8Factory.default().namespaces().create(namespace);
            if (!(await this.k8Factory.default().namespaces().has(namespace))) {
                throw new LockAcquisitionError(`failed to create the '${namespace}' namespace`);
            }
        }
        return namespace;
    }
};
LockManager = __decorate([
    injectable(),
    __param(0, inject(InjectTokens.LockRenewalService)),
    __param(1, inject(InjectTokens.SoloLogger)),
    __param(2, inject(InjectTokens.K8Factory)),
    __param(3, inject(InjectTokens.ConfigManager)),
    __param(4, inject(InjectTokens.RemoteConfigRuntimeState)),
    __metadata("design:paramtypes", [Object, Object, Object, Function, Object])
], LockManager);
export { LockManager };
//# sourceMappingURL=lock-manager.js.map