"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "FileUploadTrackerCache", {
    enumerable: true,
    get: function() {
        return FileUploadTrackerCache;
    }
});
const _correlationtokenutil = require("../utils/correlation-token.util");
const _eventconstants = require("../constants/event.constants");
class FileUploadTrackerCache {
    eventEmitter2;
    currentUploads = [];
    logger;
    constructor(loggerFactory, eventEmitter2){
        this.eventEmitter2 = eventEmitter2;
        this.logger = loggerFactory(FileUploadTrackerCache.name);
        this.eventEmitter2.on((0, _eventconstants.uploadProgressEvent)("*"), (token, progress)=>this.handleUploadProgress(token, progress));
        this.eventEmitter2.on((0, _eventconstants.uploadDoneEvent)("*"), (token)=>this.handleUploadDone(token));
        this.eventEmitter2.on((0, _eventconstants.uploadFailedEvent)("*"), (token, reason)=>this.handleUploadFailed(token, reason));
    }
    getUploads() {
        return {
            current: this.currentUploads
        };
    }
    getUpload(correlationToken) {
        return this.currentUploads.find((cu)=>cu.correlationToken === correlationToken);
    }
    addUploadTracker(multerFile, printerId) {
        const correlationToken = (0, _correlationtokenutil.generateCorrelationToken)();
        this.logger.log(`Starting upload session with token ${correlationToken}`);
        this.currentUploads.push({
            correlationToken,
            printerId,
            startedAt: Date.now(),
            multerFile,
            progress: 0,
            completed: false,
            completedAt: null,
            success: null,
            reason: null
        });
        return correlationToken;
    }
    handleUploadProgress(token, event) {
        const upload = this.getUpload(token);
        if (!upload) {
            return;
        }
        upload.progress = event.progress ?? null;
    }
    handleUploadFailed(token, reason) {
        this.logger.log(`Upload tracker ${token} completed with failure`);
        this.markUploadDone(token, false, reason);
    }
    handleUploadDone(token) {
        this.logger.log(`Upload tracker ${token} completed with success`);
        this.markUploadDone(token, true);
    }
    markUploadDone(token, success, reason) {
        const trackedUploadIndex = this.currentUploads.findIndex((cu)=>cu.correlationToken === token);
        if (trackedUploadIndex === -1) {
            this.logger.warn(`Could not mark upload tracker with correlation token '${token}' as done as it was not found.`);
            return;
        }
        const trackedUpload = this.currentUploads[trackedUploadIndex];
        trackedUpload.completed = true;
        trackedUpload.success = success;
        trackedUpload.completedAt = Date.now();
        trackedUpload.reason = reason ?? null;
    }
}

//# sourceMappingURL=file-upload-tracker.cache.js.map