"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "MulterService", {
    enumerable: true,
    get: function() {
        return MulterService;
    }
});
const _multer = /*#__PURE__*/ _interop_require_wildcard(require("multer"));
const _nodepath = require("node:path");
const _nodefs = require("node:fs");
const _fsutils = require("../../utils/fs.utils");
const _serverconstants = require("../../server.constants");
const _errorutils = require("../../utils/error.utils");
const _runtimeexceptions = require("../../exceptions/runtime.exceptions");
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
class MulterService {
    fileUploadTrackerCache;
    logger;
    constructor(loggerFactory, fileUploadTrackerCache){
        this.fileUploadTrackerCache = fileUploadTrackerCache;
        this.logger = loggerFactory(MulterService.name);
    }
    startTrackingSession(multerFile, printerId) {
        return this.fileUploadTrackerCache.addUploadTracker(multerFile, printerId);
    }
    clearUploadsFolder() {
        const fileUploadsPath = (0, _nodepath.join)((0, _fsutils.superRootPath)(), _serverconstants.AppConstants.defaultFileUploadsStorage);
        if (!(0, _nodefs.existsSync)(fileUploadsPath)) return;
        const files = (0, _nodefs.readdirSync)(fileUploadsPath, {
            withFileTypes: true
        }).filter((item)=>!item.isDirectory()).map((item)=>item.name);
        for (const file of files){
            try {
                (0, _nodefs.rmSync)((0, _nodepath.join)(fileUploadsPath, file));
            } catch (error) {
                this.logger.error(`Could not clear upload file in temporary folder ${(0, _errorutils.errorSummary)(error)}`);
            }
        }
    }
    clearUploadedFile(multerFile) {
        if ((0, _nodefs.existsSync)(multerFile.path)) {
            (0, _nodefs.rmSync)(multerFile.path);
        } else {
            this.logger.warn("Cannot unlink temporarily uploaded file as it was not found");
        }
    }
    getMulterGCodeFileFilter(storeAsFile = true) {
        return this.getMulterFileFilter(storeAsFile);
    }
    async multerLoadFileAsync(req, res, fileExtensions, storeAsFile = true) {
        const files = await new Promise((resolve, reject)=>this.getMulterFileFilter(storeAsFile)(req, res, (err)=>{
                if (err) return reject(err);
                resolve(req.files);
            }));
        this.validateUploadedFiles(files, fileExtensions, storeAsFile);
        return files;
    }
    validateUploadedFiles(files, allowedExtensions, storeAsFile) {
        if (!files?.length || !allowedExtensions?.length) return;
        for (const file of files){
            const ext = (0, _nodepath.extname)(file.originalname)?.toLowerCase();
            if (!allowedExtensions.includes(ext)) {
                if (storeAsFile && file.path && (0, _nodefs.existsSync)(file.path)) {
                    try {
                        (0, _nodefs.rmSync)(file.path);
                    } catch (e) {
                        this.logger.error(`Could not remove invalid file ${(0, _errorutils.errorSummary)(e)}`);
                    }
                }
                throw new _runtimeexceptions.ValidationException({
                    error: `Only files with extensions ${allowedExtensions.join(", ")} are allowed`
                });
            }
        }
    }
    getMulterFileFilter(storeAsFile = true) {
        return (0, _multer.default)({
            storage: storeAsFile ? (0, _multer.diskStorage)({
                destination: (0, _nodepath.join)((0, _fsutils.superRootPath)(), _serverconstants.AppConstants.defaultFileUploadsStorage)
            }) : (0, _multer.memoryStorage)()
        }).any();
    }
    getSessions() {
        return this.fileUploadTrackerCache.getUploads();
    }
}

//# sourceMappingURL=multer.service.js.map