"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "BootTask", {
    enumerable: true,
    get: function() {
        return BootTask;
    }
});
const _containertokens = require("../container.tokens");
const _serverconstants = require("../server.constants");
const _tasks = require("../tasks");
class BootTask {
    taskManagerService;
    settingsStore;
    multerService;
    printerSocketStore;
    permissionService;
    roleService;
    userService;
    floorStore;
    configService;
    typeormService;
    printerThumbnailCache;
    printFileDownloaderService;
    fileStorageService;
    logger;
    constructor(loggerFactory, taskManagerService, settingsStore, multerService, printerSocketStore, permissionService, roleService, userService, floorStore, configService, typeormService, printerThumbnailCache, printFileDownloaderService, fileStorageService){
        this.taskManagerService = taskManagerService;
        this.settingsStore = settingsStore;
        this.multerService = multerService;
        this.printerSocketStore = printerSocketStore;
        this.permissionService = permissionService;
        this.roleService = roleService;
        this.userService = userService;
        this.floorStore = floorStore;
        this.configService = configService;
        this.typeormService = typeormService;
        this.printerThumbnailCache = printerThumbnailCache;
        this.printFileDownloaderService = printFileDownloaderService;
        this.fileStorageService = fileStorageService;
        this.logger = loggerFactory(BootTask.name);
    }
    async runOnce() {
        this.taskManagerService.registerJobOrTask(_tasks.ServerTasks.SERVER_BOOT_TASK);
        this.logger.log("Running boot task once.");
        await this.run();
    }
    async run() {
        await this.typeormService.createConnection();
        this.logger.log("Ensuring file storage directories exist");
        await this.fileStorageService.ensureStorageDirectories();
        this.logger.log("Loading and synchronizing Server Settings");
        await this.settingsStore.loadSettings();
        this.logger.log("Synchronizing user permission and roles definition");
        await this.permissionService.syncPermissions();
        await this.roleService.syncRoles();
        const isDemoMode = this.configService.isDemoMode();
        if (isDemoMode) {
            this.logger.warn(`Starting in demo mode due to ${_serverconstants.AppConstants.OVERRIDE_IS_DEMO_MODE}`);
            await this.createOrUpdateDemoAccount();
            this.logger.warn(`Setting loginRequired=true and registration=false due to ${_serverconstants.AppConstants.OVERRIDE_IS_DEMO_MODE}`);
            await this.settingsStore.setLoginRequired(true);
            await this.settingsStore.setRegistrationEnabled(false);
        } else {
            const loginRequired = this.configService.get(_serverconstants.AppConstants.OVERRIDE_LOGIN_REQUIRED, null);
            if (loginRequired !== null) {
                this.logger.warn(`Setting login required due to ${_serverconstants.AppConstants.OVERRIDE_LOGIN_REQUIRED}`);
                await this.settingsStore.setLoginRequired(loginRequired === "true");
            }
            const registrationEnabled = this.configService.get(_serverconstants.AppConstants.OVERRIDE_REGISTRATION_ENABLED, null);
            if (registrationEnabled !== null) {
                this.logger.warn(`Setting registration enabled due to ${_serverconstants.AppConstants.OVERRIDE_REGISTRATION_ENABLED}`);
                await this.settingsStore.setRegistrationEnabled(registrationEnabled === "true");
            }
        }
        const overrideJwtSecret = this.configService.get(_serverconstants.AppConstants.OVERRIDE_JWT_SECRET);
        const overrideJwtExpiresIn = this.configService.get(_serverconstants.AppConstants.OVERRIDE_JWT_EXPIRES_IN);
        await this.settingsStore.persistOptionalCredentialSettings(overrideJwtSecret, overrideJwtExpiresIn);
        this.logger.log("Clearing upload folder");
        this.multerService.clearUploadsFolder();
        this.logger.log("Loading printer sockets");
        await this.printerSocketStore.loadPrinterSockets();
        this.logger.log("Loading floor store");
        await this.floorStore.loadStore();
        this.logger.log("Loading printer thumbnail cache");
        await this.printerThumbnailCache.loadCache();
        const length = await this.printerThumbnailCache.getAllValues();
        this.logger.log(`Loaded ${length.length} thumbnail(s)`);
        if (process.env.SAFEMODE_ENABLED === "true") {
            this.logger.warn("Starting in safe mode due to SAFEMODE_ENABLED");
        } else {
            _tasks.ServerTasks.BOOT_TASKS.forEach((task)=>{
                this.taskManagerService.registerJobOrTask(task);
            });
        }
        this.taskManagerService.disableJob(_containertokens.DITokens.bootTask, false);
    }
    async createOrUpdateDemoAccount() {
        const demoUsername = this.configService.get(_serverconstants.AppConstants.OVERRIDE_DEMO_USERNAME, _serverconstants.AppConstants.DEFAULT_DEMO_USERNAME);
        const demoPassword = this.configService.get(_serverconstants.AppConstants.OVERRIDE_DEMO_PASSWORD, _serverconstants.AppConstants.DEFAULT_DEMO_PASSWORD);
        const demoRole = this.configService.get(_serverconstants.AppConstants.OVERRIDE_DEMO_ROLE, _serverconstants.AppConstants.DEFAULT_DEMO_ROLE);
        const demoUserId = await this.userService.getDemoUserId();
        if (!demoUserId) {
            await this.userService.register({
                username: demoUsername,
                password: demoPassword,
                isDemoUser: true,
                isVerified: true,
                isRootUser: false,
                needsPasswordChange: false,
                roles: [
                    demoRole
                ]
            });
            this.logger.log("Created demo account");
        } else {
            await this.userService.setVerifiedById(demoUserId, true);
            await this.userService.setIsRootUserById(demoUserId, false);
            await this.userService.updatePasswordUnsafeByUsername(demoUsername, demoPassword);
            await this.userService.setUserRoles(demoUserId, [
                demoRole
            ]);
            this.logger.log("Updated demo account");
        }
    }
}

//# sourceMappingURL=boot.task.js.map