"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateFileData = void 0;
const file_type_1 = require("file-type");
const mkdirp_1 = __importDefault(require("mkdirp"));
const path_1 = __importDefault(require("path"));
const sanitize_filename_1 = __importDefault(require("sanitize-filename"));
const sharp_1 = __importDefault(require("sharp"));
const errors_1 = require("../errors");
const getImageSize_1 = __importDefault(require("./getImageSize"));
const getSafeFilename_1 = __importDefault(require("./getSafeFilename"));
const imageResizer_1 = __importDefault(require("./imageResizer"));
const canResizeImage_1 = __importDefault(require("./canResizeImage"));
const generateFileData = async ({ config, collection: { config: collectionConfig, Model, }, req, data, throwOnMissingFile, overwriteExistingFiles, }) => {
    var _a;
    let newData = data;
    const filesToSave = [];
    if (collectionConfig.upload) {
        const fileData = {};
        const { staticDir, imageSizes, disableLocalStorage, resizeOptions, formatOptions } = collectionConfig.upload;
        const { file } = req.files || {};
        if (throwOnMissingFile && !file) {
            throw new errors_1.MissingFile();
        }
        let staticPath = staticDir;
        if (staticDir.indexOf('/') !== 0) {
            staticPath = path_1.default.resolve(config.paths.configDir, staticDir);
        }
        if (!disableLocalStorage) {
            mkdirp_1.default.sync(staticPath);
        }
        if (file) {
            try {
                const shouldResize = (0, canResizeImage_1.default)(file.mimetype);
                let fsSafeName;
                let resized;
                let dimensions;
                if (shouldResize) {
                    if (resizeOptions) {
                        resized = (0, sharp_1.default)(file.data)
                            .resize(resizeOptions);
                    }
                    if (formatOptions) {
                        resized = (resized !== null && resized !== void 0 ? resized : (0, sharp_1.default)(file.data)).toFormat(formatOptions.format, formatOptions.options);
                    }
                    dimensions = await (0, getImageSize_1.default)(file);
                    fileData.width = dimensions.width;
                    fileData.height = dimensions.height;
                }
                const fileBuffer = resized ? (await resized.toBuffer()) : file.data;
                const bufferInfo = await (0, file_type_1.fromBuffer)(fileBuffer);
                let mime = (_a = bufferInfo === null || bufferInfo === void 0 ? void 0 : bufferInfo.mime) !== null && _a !== void 0 ? _a : file.mimetype;
                const ext = resized ? bufferInfo.ext : file.name.split('.').pop();
                const fileSize = fileBuffer.length;
                const baseFilename = (0, sanitize_filename_1.default)(file.name.substring(0, file.name.lastIndexOf('.')) || file.name);
                fsSafeName = `${baseFilename}.${ext}`;
                if (mime === 'application/xml' && ext === 'svg')
                    mime = 'image/svg+xml';
                if (!overwriteExistingFiles) {
                    fsSafeName = await (0, getSafeFilename_1.default)(Model, staticPath, fsSafeName);
                }
                filesToSave.push({
                    path: `${staticPath}/${fsSafeName}`,
                    buffer: fileBuffer,
                });
                fileData.filename = fsSafeName || (!overwriteExistingFiles ? await (0, getSafeFilename_1.default)(Model, staticPath, file.name) : file.name);
                fileData.filesize = fileSize || file.size;
                fileData.mimeType = mime || (await (0, file_type_1.fromBuffer)(file.data)).mime;
                if (Array.isArray(imageSizes) && shouldResize) {
                    req.payloadUploadSizes = {};
                    const { sizeData, sizesToSave } = await (0, imageResizer_1.default)({
                        req,
                        file: file.data,
                        dimensions,
                        staticPath,
                        config: collectionConfig,
                        savedFilename: fsSafeName || file.name,
                        mimeType: fileData.mimeType,
                    });
                    fileData.sizes = sizeData;
                    filesToSave.push(...sizesToSave);
                }
            }
            catch (err) {
                console.error(err);
                throw new errors_1.FileUploadError();
            }
            newData = {
                ...newData,
                ...fileData,
            };
        }
    }
    return {
        data: newData,
        files: filesToSave,
    };
};
exports.generateFileData = generateFileData;
//# sourceMappingURL=data:application/json;base64, 