"use strict";
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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SystemConfigService = void 0;
const common_1 = require("@nestjs/common");
const class_transformer_1 = require("class-transformer");
const lodash_1 = __importDefault(require("lodash"));
const config_1 = require("../config");
const decorators_1 = require("../decorators");
const system_config_dto_1 = require("../dtos/system-config.dto");
const enum_1 = require("../enum");
const base_service_1 = require("./base.service");
const config_2 = require("../utils/config");
const object_1 = require("../utils/object");
let SystemConfigService = class SystemConfigService extends base_service_1.BaseService {
    async onBootstrap() {
        const config = await this.getConfig({ withCache: false });
        await this.eventRepository.emit('ConfigInit', { newConfig: config });
        if (process.env.IMMICH_MACHINE_LEARNING_PING_TIMEOUT ||
            process.env.IMMICH_MACHINE_LEARNING_AVAILABILITY_BACKOFF_TIME) {
            this.logger.deprecate('IMMICH_MACHINE_LEARNING_PING_TIMEOUT and MACHINE_LEARNING_AVAILABILITY_BACKOFF_TIME have been moved to system config(`machineLearning.availabilityChecks`) and will be removed in a future release.');
        }
    }
    onShutdown() {
        this.machineLearningRepository.teardown();
    }
    async getSystemConfig() {
        const config = await this.getConfig({ withCache: false });
        return (0, system_config_dto_1.mapConfig)(config);
    }
    getDefaults() {
        return (0, system_config_dto_1.mapConfig)(config_1.defaults);
    }
    onConfigInit({ newConfig: { logging, machineLearning } }) {
        const { logLevel: envLevel } = this.configRepository.getEnv();
        const configLevel = logging.enabled ? logging.level : false;
        const level = envLevel ?? configLevel;
        this.logger.setLogLevel(level);
        this.logger.log(`LogLevel=${level} ${envLevel ? '(set via IMMICH_LOG_LEVEL)' : '(set via system config)'}`);
        this.machineLearningRepository.setup(machineLearning);
    }
    onConfigUpdate({ newConfig }) {
        this.onConfigInit({ newConfig });
        (0, config_2.clearConfigCache)();
    }
    onConfigValidate({ newConfig, oldConfig }) {
        const { logLevel } = this.configRepository.getEnv();
        if (!lodash_1.default.isEqual((0, class_transformer_1.instanceToPlain)(newConfig.logging), oldConfig.logging) && logLevel) {
            throw new Error('Logging cannot be changed while the environment variable IMMICH_LOG_LEVEL is set.');
        }
    }
    async updateSystemConfig(dto) {
        const { configFile } = this.configRepository.getEnv();
        if (configFile) {
            throw new common_1.BadRequestException('Cannot update configuration while IMMICH_CONFIG_FILE is in use');
        }
        const oldConfig = await this.getConfig({ withCache: false });
        try {
            await this.eventRepository.emit('ConfigValidate', { newConfig: (0, object_1.toPlainObject)(dto), oldConfig });
        }
        catch (error) {
            this.logger.warn(`Unable to save system config due to a validation error: ${error}`);
            throw new common_1.BadRequestException(error instanceof Error ? error.message : error);
        }
        const newConfig = await this.updateConfig(dto);
        await this.eventRepository.emit('ConfigUpdate', { newConfig, oldConfig });
        return (0, system_config_dto_1.mapConfig)(newConfig);
    }
    async getCustomCss() {
        const { theme } = await this.getConfig({ withCache: false });
        return theme.customCss;
    }
};
exports.SystemConfigService = SystemConfigService;
__decorate([
    (0, decorators_1.OnEvent)({ name: 'AppBootstrap', priority: enum_1.BootstrapEventPriority.SystemConfig }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], SystemConfigService.prototype, "onBootstrap", null);
__decorate([
    (0, decorators_1.OnEvent)({ name: 'AppShutdown' }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], SystemConfigService.prototype, "onShutdown", null);
__decorate([
    (0, decorators_1.OnEvent)({ name: 'ConfigInit', priority: -100 }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], SystemConfigService.prototype, "onConfigInit", null);
__decorate([
    (0, decorators_1.OnEvent)({ name: 'ConfigUpdate', server: true }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], SystemConfigService.prototype, "onConfigUpdate", null);
__decorate([
    (0, decorators_1.OnEvent)({ name: 'ConfigValidate' }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], SystemConfigService.prototype, "onConfigValidate", null);
exports.SystemConfigService = SystemConfigService = __decorate([
    (0, common_1.Injectable)()
], SystemConfigService);
//# sourceMappingURL=system-config.service.js.map