"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "MulterService", {
    enumerable: true,
    get: function() {
        return MulterService;
    }
});
const _multer = /*#__PURE__*/ _interop_require_default(require("multer"));
const _path = require("path");
const _fs = require("fs");
const _fsutils = require("../../utils/fs.utils");
const _serverconstants = require("../../server.constants");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
class MulterService {
    fileUploadTrackerCache;
    httpClient;
    constructor({ fileUploadTrackerCache, httpClient }){
        this.fileUploadTrackerCache = fileUploadTrackerCache;
        this.httpClient = httpClient;
    }
    getNewestFile(collection) {
        const dirPath = this.collectionPath(collection);
        const files = this.orderRecentFiles(dirPath);
        const latestFile = files.length ? files[0] : undefined;
        return latestFile ? (0, _path.join)(dirPath, latestFile.file) : undefined;
    }
    clearUploadsFolder() {
        const fileStoragePath = (0, _path.join)((0, _fsutils.superRootPath)(), _serverconstants.AppConstants.defaultFileStorageFolder);
        if (!(0, _fs.existsSync)(fileStoragePath)) return;
        const files = (0, _fs.readdirSync)(fileStoragePath, {
            withFileTypes: true
        }).filter((item)=>!item.isDirectory()).map((item)=>item.name);
        for (const file of files){
            (0, _fs.unlink)((0, _path.join)(fileStoragePath, file), (err)=>{
                if (err) throw err;
            });
        }
    }
    fileExists(downloadFilename, collection) {
        const downloadPath = (0, _path.join)((0, _fsutils.superRootPath)(), _serverconstants.AppConstants.defaultFileStorageFolder, collection, downloadFilename);
        return (0, _fs.existsSync)(downloadPath);
    }
    async downloadFile(downloadUrl, downloadFilename, collection) {
        const downloadFolder = (0, _path.join)((0, _fsutils.superRootPath)(), _serverconstants.AppConstants.defaultFileStorageFolder, collection);
        if (!(0, _fs.existsSync)(downloadFolder)) {
            (0, _fs.mkdirSync)(downloadFolder, {
                recursive: true
            });
        }
        const downloadPath = (0, _path.join)((0, _fsutils.superRootPath)(), _serverconstants.AppConstants.defaultFileStorageFolder, collection, downloadFilename);
        const fileStream = (0, _fs.createWriteStream)(downloadPath);
        const res = await this.httpClient.get(downloadUrl);
        return await new Promise((resolve, reject)=>{
            fileStream.write(res.data);
            fileStream.on("error", (err)=>{
                return reject(err);
            });
            fileStream.on("finish", async ()=>{
                return resolve(null);
            });
            fileStream.on("close", async ()=>{
                return resolve(null);
            });
            resolve(null);
        });
    }
    getMulterGCodeFileFilter(storeAsFile = true) {
        return this.getMulterFileFilter(".gcode", storeAsFile);
    }
    async multerLoadFileAsync(req, res, fileExtension, storeAsFile = true) {
        return await new Promise((resolve, reject)=>this.getMulterFileFilter(fileExtension, storeAsFile)(req, res, (err)=>{
                if (err) {
                    return reject(err);
                }
                resolve(req.files);
            }));
    }
    getMulterFileFilter(fileExtension, storeAsFile = true) {
        return (0, _multer.default)({
            storage: storeAsFile ? _multer.default.diskStorage({
                destination: (0, _path.join)((0, _fsutils.superRootPath)(), _serverconstants.AppConstants.defaultFileStorageFolder)
            }) : _multer.default.memoryStorage(),
            fileFilter: this.multerFileFilter(fileExtension)
        }).any();
    }
    multerFileFilter(extension) {
        return (req, file, callback)=>{
            const ext = (0, _path.extname)(file.originalname);
            if (extension?.length && ext !== extension) {
                return callback(new Error(`Only files with extension ${extension} are allowed`));
            }
            return callback(null, true);
        };
    }
    startTrackingSession(multerFile) {
        return this.fileUploadTrackerCache.addUploadTracker(multerFile);
    }
    getSessions() {
        return this.fileUploadTrackerCache.getUploads();
    }
    orderRecentFiles = (dir)=>{
        return (0, _fs.readdirSync)(dir).filter((file)=>(0, _fs.lstatSync)((0, _path.join)(dir, file)).isFile()).map((file)=>({
                file,
                mtime: (0, _fs.lstatSync)((0, _path.join)(dir, file)).mtime
            })).sort((a, b)=>b.mtime.getTime() - a.mtime.getTime());
    };
    collectionPath(collection) {
        return (0, _path.join)((0, _fsutils.superRootPath)(), _serverconstants.AppConstants.defaultFileStorageFolder, collection);
    }
}

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