"use strict";
/*
 * @adonisjs/bodyparser
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
Object.defineProperty(exports, "__esModule", { value: true });
/// <reference path="../../adonis-typings/bodyparser.ts" />
const utils_1 = require("@poppinss/utils");
const File_1 = require("../Multipart/File");
/**
 * Updates the validation options on the file instance
 */
function setFileOptions(file, options) {
    if (file.sizeLimit === undefined && options && options.size) {
        file.sizeLimit = options.size;
    }
    if (file.allowedExtensions === undefined && options && options.extnames) {
        file.allowedExtensions = options.extnames;
    }
}
/**
 * A boolean to know if file is an instance of multipart
 * file class
 */
function isInstanceOfFile(file) {
    return file && file instanceof File_1.File;
}
/**
 * Extend the Request class by adding `file` and `files` macro to read processed
 * files
 */
function extendRequest(Request) {
    /**
     * Fetch a single file
     */
    Request.macro('file', function getFile(key, options) {
        let file = utils_1.lodash.get(this.allFiles(), key);
        file = Array.isArray(file) ? file[0] : file;
        if (!isInstanceOfFile(file)) {
            return null;
        }
        setFileOptions(file, options);
        file.validate();
        return file;
    });
    /**
     * Fetch an array of files
     */
    Request.macro('files', function getFiles(key, options) {
        let files = utils_1.lodash.get(this.allFiles(), key);
        files = Array.isArray(files) ? files : files ? [files] : [];
        return files.filter(isInstanceOfFile).map((file) => {
            setFileOptions(file, options);
            file.validate();
            return file;
        });
    });
    /**
     * Fetch all files
     */
    Request.macro('allFiles', function allFiles() {
        return this['__raw_files'] || {};
    });
}
exports.default = extendRequest;
