"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 });
exports.FormFields = void 0;
const utils_1 = require("@poppinss/utils");
/**
 * A jar of form fields to store form data by handling
 * array gracefully
 */
class FormFields {
    constructor(config) {
        this.config = config;
        this.fields = {};
    }
    /**
     * Add a new key/value pair. The keys with array like
     * expressions are handled properly.
     *
     * @example
     * ```
     * formfields.add('username', 'virk')
     *
     * // array
     * formfields.add('username[]', 'virk')
     * formfields.add('username[]', 'nikk')
     *
     * // Indexed keys are orderd properly
     * formfields.add('username[1]', 'virk')
     * formfields.add('username[0]', 'nikk')
     * ```
     */
    add(key, value) {
        let isArray = false;
        /**
         * Convert empty strings to null
         */
        if (this.config.convertEmptyStringsToNull && value === '') {
            value = null;
        }
        /**
         * Drop `[]` without indexes, since lodash `_.set` and
         * `_.get` methods needs the index or plain key.
         */
        key = key.replace(/\[]$/, () => {
            isArray = true;
            return '';
        });
        /**
         * Check to see if value exists or set it (if missing)
         */
        const existingValue = utils_1.lodash.get(this.fields, key);
        if (!existingValue) {
            utils_1.lodash.set(this.fields, key, isArray ? [value] : value);
            return;
        }
        /**
         * Mutate existing value if it's an array
         */
        if (existingValue instanceof Array) {
            existingValue.push(value);
            return;
        }
        /**
         * Set new value + existing value
         */
        utils_1.lodash.set(this.fields, key, [existingValue, value]);
    }
    /**
     * Returns the copy of form fields
     */
    get() {
        return this.fields;
    }
}
exports.FormFields = FormFields;
