"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const express_async_handler_1 = __importDefault(require("express-async-handler"));
const busboy_1 = __importDefault(require("busboy"));
const sanitize_query_1 = __importDefault(require("../middleware/sanitize-query"));
const FilesService = __importStar(require("../services/files"));
const use_collection_1 = __importDefault(require("../middleware/use-collection"));
const router = express_1.default.Router();
router.use(use_collection_1.default('directus_files'));
const multipartHandler = (operation) => express_async_handler_1.default((req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
    const busboy = new busboy_1.default({ headers: req.headers });
    const savedFiles = [];
    const accountability = {
        role: req.role,
        admin: req.admin,
        ip: req.ip,
        userAgent: req.get('user-agent'),
        user: req.user,
    };
    /**
     * The order of the fields in multipart/form-data is important. We require that all fields
     * are provided _before_ the files. This allows us to set the storage location, and create
     * the row in directus_files async during the upload of the actual file.
     */
    let disk = process.env.STORAGE_LOCATIONS.split(',')[0].trim();
    let payload = {};
    let fileCount = 0;
    busboy.on('field', (fieldname, val) => {
        if (fieldname === 'storage') {
            disk = val;
        }
        payload[fieldname] = val;
    });
    busboy.on('file', (fieldname, fileStream, filename, encoding, mimetype) => __awaiter(void 0, void 0, void 0, function* () {
        fileCount++;
        payload = Object.assign(Object.assign({}, payload), { filename_disk: filename, filename_download: filename, type: mimetype });
        if (!payload.storage) {
            payload.storage = disk;
        }
        if (req.user) {
            payload.uploaded_by = req.user;
        }
        try {
            if (operation === 'create') {
                const pk = yield FilesService.createFile(payload, fileStream, accountability);
                const file = yield FilesService.readFile(pk, req.sanitizedQuery, accountability);
                savedFiles.push(file);
                tryDone();
            }
            else {
                const pk = yield FilesService.updateFile(req.params.pk, payload, accountability, fileStream);
                const file = yield FilesService.readFile(pk, req.sanitizedQuery, accountability);
                savedFiles.push(file);
                tryDone();
            }
        }
        catch (err) {
            busboy.emit('error', err);
        }
    }));
    busboy.on('error', (error) => {
        next(error);
    });
    busboy.on('finish', () => {
        tryDone();
    });
    req.pipe(busboy);
    function tryDone() {
        if (savedFiles.length === fileCount) {
            if (fileCount === 1) {
                return res.status(200).json({ data: savedFiles[0] });
            }
            else {
                return res.status(200).json({ data: savedFiles });
            }
        }
    }
}));
router.post('/', sanitize_query_1.default, multipartHandler('create'));
router.get('/', sanitize_query_1.default, express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const records = yield FilesService.readFiles(req.sanitizedQuery, {
        role: req.role,
        admin: req.admin,
    });
    return res.json({ data: records || null });
})));
router.get('/:pk', sanitize_query_1.default, express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const record = yield FilesService.readFile(req.params.pk, req.sanitizedQuery, {
        role: req.role,
        admin: req.admin,
    });
    return res.json({ data: record || null });
})));
router.patch('/:pk', sanitize_query_1.default, express_async_handler_1.default((req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
    let file;
    if (req.is('multipart/form-data')) {
        file = yield multipartHandler('update')(req, res, next);
    }
    else {
        const pk = yield FilesService.updateFile(req.params.pk, req.body, {
            role: req.role,
            admin: req.admin,
            ip: req.ip,
            userAgent: req.get('user-agent'),
            user: req.user,
        });
        file = yield FilesService.readFile(pk, req.sanitizedQuery, {
            role: req.role,
            admin: req.admin,
        });
    }
    return res.status(200).json({ data: file || null });
})));
router.delete('/:pk', express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    yield FilesService.deleteFile(req.params.pk, {
        role: req.role,
        admin: req.admin,
        ip: req.ip,
        userAgent: req.get('user-agent'),
        user: req.user,
    });
    return res.status(200).end();
})));
exports.default = router;
