"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "PrintQueueController", {
    enumerable: true,
    get: function() {
        return PrintQueueController;
    }
});
const _awilixexpress = require("awilix-express");
const _serverconstants = require("../server.constants");
const _express = require("express");
const _authenticate = require("../middleware/authenticate");
const _authorizationconstants = require("../constants/authorization.constants");
const _printqueueservice = require("../services/print-queue.service");
const _loggerfactory = require("../handlers/logger-factory");
const _paramconvertermiddleware = require("../middleware/param-converter.middleware");
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);
}
class PrintQueueController {
    printQueueService;
    logger;
    constructor(loggerFactory, printQueueService){
        this.printQueueService = printQueueService;
        this.logger = loggerFactory(PrintQueueController.name);
    }
    async getGlobalQueue(req, res) {
        try {
            const page = Number.parseInt(req.query.page) || 1;
            const pageSize = Number.parseInt(req.query.pageSize) || 50;
            if (page < 1 || pageSize < 1 || pageSize > 200) {
                res.status(400).send({
                    error: "Invalid page or pageSize parameters"
                });
                return;
            }
            const skip = (page - 1) * pageSize;
            const [jobs, totalCount] = await this.printQueueService.printJobRepository.findAndCount({
                where: {
                    status: "QUEUED"
                },
                order: {
                    printerId: "ASC",
                    queuePosition: "ASC"
                },
                relations: [
                    'printer'
                ],
                take: pageSize,
                skip: skip
            });
            const queueItems = jobs.map((job)=>({
                    jobId: job.id,
                    fileName: job.fileName,
                    printerId: job.printerId,
                    printerName: job.printerName || job.printer?.name,
                    queuePosition: job.queuePosition,
                    status: job.status,
                    createdAt: job.createdAt,
                    estimatedTimeSeconds: job.metadata?.gcodePrintTimeSeconds,
                    filamentGrams: job.metadata?.filamentUsedGrams
                }));
            res.send({
                items: queueItems,
                page,
                pageSize,
                totalCount,
                totalPages: Math.ceil(totalCount / pageSize)
            });
        } catch (error) {
            this.logger.error(`Failed to get global queue: ${error}`);
            res.status(500).send({
                error: "Failed to get global queue"
            });
        }
    }
    async getQueue(req, res) {
        const printerId = req.local.printerId;
        try {
            const queue = await this.printQueueService.getQueue(printerId);
            res.send({
                printerId,
                queue,
                count: queue.length
            });
        } catch (error) {
            this.logger.error(`Failed to get queue for printer ${printerId}: ${error}`);
            res.status(500).send({
                error: "Failed to get queue"
            });
        }
    }
    async addToQueue(req, res) {
        const printerId = req.local.printerId;
        const jobId = req.local.jobId;
        const position = req.body.position === undefined ? undefined : Number.parseInt(req.body.position);
        try {
            await this.printQueueService.addToQueue(printerId, jobId, position);
            const queue = await this.printQueueService.getQueue(printerId);
            res.send({
                message: "Job added to queue",
                printerId,
                jobId,
                position,
                queue
            });
        } catch (error) {
            this.logger.error(`Failed to add job ${jobId} to queue: ${error}`);
            res.status(500).send({
                error: "Failed to add to queue",
                message: error instanceof Error ? error.message : "Unknown error"
            });
        }
    }
    async reorderQueue(req, res) {
        const printerId = req.local.printerId;
        const jobIds = req.body.jobIds;
        if (!Array.isArray(jobIds)) {
            res.status(400).send({
                error: "jobIds must be an array"
            });
            return;
        }
        try {
            await this.printQueueService.reorderQueue(printerId, jobIds);
            const queue = await this.printQueueService.getQueue(printerId);
            res.send({
                message: "Queue reordered",
                printerId,
                queue
            });
        } catch (error) {
            this.logger.error(`Failed to reorder queue for printer ${printerId}: ${error}`);
            res.status(500).send({
                error: "Failed to reorder queue",
                message: error instanceof Error ? error.message : "Unknown error"
            });
        }
    }
    async clearQueue(req, res) {
        const printerId = req.local.printerId;
        try {
            await this.printQueueService.clearQueue(printerId);
            res.send({
                message: "Queue cleared",
                printerId
            });
        } catch (error) {
            this.logger.error(`Failed to clear queue for printer ${printerId}: ${error}`);
            res.status(500).send({
                error: "Failed to clear queue",
                message: error instanceof Error ? error.message : "Unknown error"
            });
        }
    }
    async removeFromQueue(req, res) {
        const printerId = req.local.printerId;
        const jobId = req.local.jobId;
        try {
            await this.printQueueService.removeFromQueue(jobId);
            const queue = await this.printQueueService.getQueue(printerId);
            res.send({
                message: "Job removed from queue",
                printerId,
                jobId,
                queue
            });
        } catch (error) {
            this.logger.error(`Failed to remove job ${jobId} from queue: ${error}`);
            res.status(500).send({
                error: "Failed to remove from queue",
                message: error instanceof Error ? error.message : "Unknown error"
            });
        }
    }
    async getNextInQueue(req, res) {
        const printerId = req.local.printerId;
        try {
            const nextJob = await this.printQueueService.getNextInQueue(printerId);
            res.send({
                printerId,
                nextJob
            });
        } catch (error) {
            this.logger.error(`Failed to get next job for printer ${printerId}: ${error}`);
            res.status(500).send({
                error: "Failed to get next job"
            });
        }
    }
    async processQueue(req, res) {
        const printerId = req.local.printerId;
        try {
            const nextJob = await this.printQueueService.processQueue(printerId);
            if (!nextJob) {
                res.send({
                    message: "Queue is empty",
                    printerId,
                    nextJob: null
                });
                return;
            }
            res.send({
                message: "Processing next job in queue",
                printerId,
                nextJob
            });
        } catch (error) {
            this.logger.error(`Failed to process queue for printer ${printerId}: ${error}`);
            res.status(500).send({
                error: "Failed to process queue",
                message: error instanceof Error ? error.message : "Unknown error"
            });
        }
    }
    async submitToPrinter(req, res) {
        const printerId = req.local.printerId;
        const jobId = req.local.jobId;
        try {
            await this.printQueueService.submitToPrinter(printerId, jobId);
            res.send({
                message: "Job submitted to printer for printing",
                printerId,
                jobId
            });
        } catch (error) {
            this.logger.error(`Failed to submit job ${jobId} to printer ${printerId}: ${error}`);
            res.status(500).send({
                error: "Failed to submit job to printer",
                message: error instanceof Error ? error.message : "Unknown error"
            });
        }
    }
}
_ts_decorate([
    (0, _awilixexpress.GET)(),
    _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)
], PrintQueueController.prototype, "getGlobalQueue", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/:printerId"),
    (0, _awilixexpress.before)([
        (0, _paramconvertermiddleware.ParamId)("printerId")
    ]),
    _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)
], PrintQueueController.prototype, "getQueue", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/:printerId/add/:jobId"),
    (0, _awilixexpress.before)([
        (0, _paramconvertermiddleware.ParamId)("printerId"),
        (0, _paramconvertermiddleware.ParamId)("jobId")
    ]),
    _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)
], PrintQueueController.prototype, "addToQueue", null);
_ts_decorate([
    (0, _awilixexpress.PUT)(),
    (0, _awilixexpress.route)("/:printerId/reorder"),
    (0, _awilixexpress.before)([
        (0, _paramconvertermiddleware.ParamId)("printerId")
    ]),
    _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)
], PrintQueueController.prototype, "reorderQueue", null);
_ts_decorate([
    (0, _awilixexpress.DELETE)(),
    (0, _awilixexpress.route)("/:printerId/clear"),
    (0, _awilixexpress.before)([
        (0, _paramconvertermiddleware.ParamId)("printerId")
    ]),
    _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)
], PrintQueueController.prototype, "clearQueue", null);
_ts_decorate([
    (0, _awilixexpress.DELETE)(),
    (0, _awilixexpress.route)("/:printerId/:jobId"),
    (0, _awilixexpress.before)([
        (0, _paramconvertermiddleware.ParamId)("printerId"),
        (0, _paramconvertermiddleware.ParamId)("jobId")
    ]),
    _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)
], PrintQueueController.prototype, "removeFromQueue", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/:printerId/next"),
    (0, _awilixexpress.before)([
        (0, _paramconvertermiddleware.ParamId)("printerId")
    ]),
    _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)
], PrintQueueController.prototype, "getNextInQueue", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/:printerId/process"),
    (0, _awilixexpress.before)([
        (0, _paramconvertermiddleware.ParamId)("printerId")
    ]),
    _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)
], PrintQueueController.prototype, "processQueue", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/:printerId/submit/:jobId"),
    (0, _awilixexpress.before)([
        (0, _paramconvertermiddleware.ParamId)("printerId"),
        (0, _paramconvertermiddleware.ParamId)("jobId")
    ]),
    _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)
], PrintQueueController.prototype, "submitToPrinter", null);
PrintQueueController = _ts_decorate([
    (0, _awilixexpress.route)(_serverconstants.AppConstants.apiRoute + "/print-queue"),
    (0, _awilixexpress.before)([
        (0, _authenticate.authenticate)(),
        (0, _authenticate.authorizeRoles)([
            _authorizationconstants.ROLES.ADMIN,
            _authorizationconstants.ROLES.OPERATOR
        ])
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _loggerfactory.ILoggerFactory === "undefined" ? Object : _loggerfactory.ILoggerFactory,
        typeof _printqueueservice.PrintQueueService === "undefined" ? Object : _printqueueservice.PrintQueueService
    ])
], PrintQueueController);

//# sourceMappingURL=print-queue.controller.js.map