"use strict";

const React = require("react");
const cold = require("react-hot-loader").cold;
const formSerialize = require("form-serialize");

const context = require("./context");

module.exports = cold(function Form(props) {
	let { handle } = React.useContext(context);

	let {
		method, url, children, multipart,
		/* We ignore the following two, as they are covered by `multipart` and `url` respectively. */
		enctype: _enctype,
		action: _action,
		...rest
	} = props;

	function submitFormToRouter(form) {
		let serializedFormData = formSerialize(form, {hash: true, empty: true, disabled: true});

		return handle(method, url, serializedFormData, {
			multipart: (multipart === true)
		});
	}

	function handleSubmit(event) {
		event.preventDefault();
		return submitFormToRouter(event.target);
	}

	return (
		<form onSubmit={handleSubmit} encType={(multipart === true ? "multipart/form-data" : null)} {...rest}>
			{children}
		</form>
	);
});
