"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "PrinterThumbnailCache", {
    enumerable: true,
    get: function() {
        return PrinterThumbnailCache;
    }
});
const _keydiffcache = require("../utils/cache/key-diff.cache");
class PrinterThumbnailCache extends _keydiffcache.KeyDiffCache {
    printJobService;
    fileStorageService;
    logger;
    constructor(loggerFactory, printJobService, fileStorageService){
        super(), this.printJobService = printJobService, this.fileStorageService = fileStorageService;
        this.logger = loggerFactory(PrinterThumbnailCache.name);
    }
    async loadCache() {
        this.logger.log("Loading printer thumbnail cache from print jobs...");
        try {
            const recentJobs = await this.printJobService.printJobRepository.createQueryBuilder("job").select("job.printerId").addSelect("MAX(job.endedAt)", "maxEndedAt").where("job.fileStorageId IS NOT NULL").andWhere("job.analysisState = :state", {
                state: "ANALYZED"
            }).groupBy("job.printerId").getRawMany();
            let loadedCount = 0;
            for (const result of recentJobs){
                const printerId = result.job_printerId;
                if (printerId) {
                    try {
                        await this.loadPrinterThumbnail(printerId);
                        loadedCount++;
                    } catch (error) {
                        this.logger.warn(`Failed to load thumbnail for printer ${printerId}: ${error}`);
                    }
                }
            }
            this.logger.log(`Loaded ${loadedCount} printer thumbnails from print jobs`);
        } catch (error) {
            this.logger.error("Failed to load thumbnail cache", error);
        }
    }
    async loadPrinterThumbnail(printerId) {
        try {
            const job = await this.printJobService.printJobRepository.findOne({
                where: {
                    printerId,
                    analysisState: "ANALYZED"
                },
                order: {
                    endedAt: "DESC",
                    startedAt: "DESC",
                    createdAt: "DESC"
                }
            });
            if (!job || !job.fileStorageId) {
                this.logger.debug(`No suitable job found for printer ${printerId}`);
                return;
            }
            const metadata = await this.fileStorageService.loadMetadata(job.fileStorageId);
            const thumbnails = metadata?._thumbnails || [];
            if (thumbnails.length === 0) {
                this.logger.debug(`No thumbnails found for job ${job.id}`);
                return;
            }
            const thumbnailBuffer = await this.fileStorageService.getThumbnail(job.fileStorageId, 0);
            if (!thumbnailBuffer) {
                this.logger.warn(`Thumbnail file not found for job ${job.id}`);
                return;
            }
            const thumbnailBase64 = thumbnailBuffer.toString("base64");
            await this.setPrinterThumbnail(printerId, thumbnailBase64, job.id, job.fileName);
            this.logger.debug(`Loaded thumbnail for printer ${printerId} from job ${job.id}`);
        } catch (error) {
            this.logger.error(`Failed to load thumbnail for printer ${printerId}: ${error}`);
            throw error;
        }
    }
    async setPrinterThumbnail(printerId, thumbnailBase64, jobId, fileName) {
        await this.setKeyValue(printerId, {
            printerId,
            thumbnailBase64,
            jobId,
            fileName,
            updatedAt: new Date()
        });
    }
    async unsetPrinterThumbnail(printerId) {
        await this.deleteKeyValue(printerId);
    }
    async resetCache() {
        this.logger.log("Resetting printer thumbnail cache");
        this.keyValueStore.clear();
        this.resetDiffs();
    }
    async handleJobCompleted(printerId, jobId) {
        try {
            this.logger.log(`Updating thumbnail for printer ${printerId} after job ${jobId} completed`);
            await this.loadPrinterThumbnail(printerId);
        } catch (error) {
            this.logger.error(`Failed to update thumbnail after job completion: ${error}`);
        }
    }
    async handleJobStarted(printerId, jobId) {
        try {
            const job = await this.printJobService.printJobRepository.findOne({
                where: {
                    id: jobId
                }
            });
            if (!job || !job.fileStorageId) {
                return;
            }
            const metadata = await this.fileStorageService.loadMetadata(job.fileStorageId);
            const thumbnails = metadata?._thumbnails || [];
            if (thumbnails.length === 0) {
                return;
            }
            const thumbnailBuffer = await this.fileStorageService.getThumbnail(job.fileStorageId, 0);
            if (!thumbnailBuffer) {
                return;
            }
            const thumbnailBase64 = thumbnailBuffer.toString("base64");
            await this.setPrinterThumbnail(printerId, thumbnailBase64, job.id, job.fileName);
            this.logger.debug(`Updated thumbnail for printer ${printerId} from started job ${job.id}`);
        } catch (error) {
            this.logger.error(`Failed to update thumbnail after job start: ${error}`);
        }
    }
}

//# sourceMappingURL=printer-thumbnail.cache.js.map