"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "PluginFirmwareUpdateController", {
    enumerable: true,
    get: function() {
        return PluginFirmwareUpdateController;
    }
});
const _awilixexpress = require("awilix-express");
const _serverconstants = require("../server.constants");
const _authenticate = require("../middleware/authenticate");
const _authorizationconstants = require("../constants/authorization.constants");
const _printer = require("../middleware/printer");
const _validators = require("../handlers/validators");
const _express = require("express");
function _ts_decorate(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;
}
function _ts_metadata(k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
}
const cacheKey = "firmware-state";
class PluginFirmwareUpdateController {
    cacheManager;
    printerCache;
    pluginFirmwareUpdateService;
    logger;
    constructor({ cacheManager, printerCache, pluginFirmwareUpdateService, loggerFactory }){
        this.cacheManager = cacheManager;
        this.printerCache = printerCache;
        this.pluginFirmwareUpdateService = pluginFirmwareUpdateService;
        this.logger = loggerFactory(PluginFirmwareUpdateController.name);
    }
    async listUpdateState(req, res) {
        const result = await this.performScanOnPrinters();
        res.send(result);
    }
    async syncFirmwareReleasesCache(req, res) {
        const releases = await this.pluginFirmwareUpdateService.queryGithubPrusaFirmwareReleasesCache();
        res.send(releases);
    }
    async downloadFirmware(req, res) {
        await this.pluginFirmwareUpdateService.downloadFirmware();
        res.send({});
    }
    async scanPrinterFirmwareVersions(req, res) {
        const result = await this.performScanOnPrinters();
        res.send(result);
    }
    async isPluginInstalled(req, res) {
        const { printerLogin } = (0, _validators.getScopedPrinter)(req);
        const isInstalled = await this.pluginFirmwareUpdateService.isPluginInstalled(printerLogin);
        res.send({
            isInstalled
        });
    }
    async installFirmwareUpdatePlugin(req, res) {
        const { printerLogin } = (0, _validators.getScopedPrinter)(req);
        const isInstalled = await this.pluginFirmwareUpdateService.isPluginInstalled(printerLogin);
        if (!isInstalled) {
            await this.pluginFirmwareUpdateService.installPlugin(printerLogin);
            res.send({
                isInstalled,
                installing: true
            });
            return;
        }
        res.send({
            isInstalled,
            installing: false
        });
    }
    async getFirmwareUpdaterStatus(req, res) {
        const { printerLogin } = (0, _validators.getScopedPrinter)(req);
        const status = await this.pluginFirmwareUpdateService.getPluginFirmwareStatus(printerLogin);
        res.send(status);
    }
    async configurePluginSettings(req, res) {
        const { printerLogin } = (0, _validators.getScopedPrinter)(req);
        const response = await this.pluginFirmwareUpdateService.configureFirmwareUpdaterSettings(printerLogin);
        res.send(response);
    }
    async flashFirmware(req, res) {
        const { printerLogin, currentPrinterId } = (0, _validators.getScopedPrinter)(req);
        await this.pluginFirmwareUpdateService.flashPrusaFirmware(currentPrinterId, printerLogin);
        res.send({});
    }
    async performScanOnPrinters() {
        const printers = await this.printerCache.listCachedPrinters();
        const printerFirmwareStates = [];
        const failureStates = [];
        for (let printer of printers){
            try {
                const loginDto = await this.printerCache.getLoginDtoAsync(printer.id);
                const isInstalled = await this.pluginFirmwareUpdateService.isPluginInstalled(loginDto);
                let version;
                if (isInstalled) {
                    version = await this.pluginFirmwareUpdateService.getPrinterFirmwareVersion(loginDto);
                }
                printerFirmwareStates.push({
                    id: printer.id,
                    firmware: version,
                    printerName: printer.name,
                    pluginInstalled: isInstalled
                });
            } catch (e) {
                this.logger.error("Firmware updater plugin scan failed with an error");
                failureStates.push({
                    id: printer.id,
                    printerName: printer.name,
                    error: e
                });
            }
        }
        const result = {
            firmwareStates: printerFirmwareStates,
            failures: failureStates
        };
        await this.cacheManager.set(cacheKey, result, {
            ttl: 3600 * 4
        });
        return result;
    }
}
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PluginFirmwareUpdateController.prototype, "listUpdateState", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/releases/sync"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PluginFirmwareUpdateController.prototype, "syncFirmwareReleasesCache", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/download-firmware"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PluginFirmwareUpdateController.prototype, "downloadFirmware", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/scan"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PluginFirmwareUpdateController.prototype, "scanPrinterFirmwareVersions", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/:id/is-plugin-installed"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PluginFirmwareUpdateController.prototype, "isPluginInstalled", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/:id/install-firmware-update-plugin"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PluginFirmwareUpdateController.prototype, "installFirmwareUpdatePlugin", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/:id/status"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PluginFirmwareUpdateController.prototype, "getFirmwareUpdaterStatus", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/:id/configure-plugin-settings"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PluginFirmwareUpdateController.prototype, "configurePluginSettings", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/:id/flash-firmware"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], PluginFirmwareUpdateController.prototype, "flashFirmware", null);
PluginFirmwareUpdateController = _ts_decorate([
    (0, _awilixexpress.route)(_serverconstants.AppConstants.apiRoute + "/plugin/firmware-update"),
    (0, _awilixexpress.before)([
        (0, _authenticate.authenticate)(),
        (0, _authenticate.authorizeRoles)([
            _authorizationconstants.ROLES.OPERATOR,
            _authorizationconstants.ROLES.ADMIN
        ]),
        (0, _printer.printerResolveMiddleware)()
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        Object
    ])
], PluginFirmwareUpdateController);

//# sourceMappingURL=plugin-firmware-update.controller.js.map