"use strict";

// Update the form with the answer
function doActions(parent, data) {
	// Redirect the user
	if (data.redirect !== "") {
		window.location.replace(data.redirect);
	}

	// Refresh the page
	if (data.refresh) {
		if (data.error == '' && data.message == '') {
			window.location.reload();
		} else {
			setTimeout(function() {
				window.location.reload();
			}, 3000);
		}
	}

	// Reset the form
	if (data.reset) {
		parent.reset();
	}

	// Update the form error
	parent.querySelector('.form-error').innerHTML = data.error;
	setTimeout(function() {
		parent.querySelector('.form-error').innerHTML = '';
	}, 3000);

	// Update the form message
	parent.querySelector('.form-message').innerHTML = data.message;
	setTimeout(function() {
		parent.querySelector('.form-message').innerHTML = '';
	}, 3000);
}

// Add event listener
document.querySelectorAll('.ajax-form').forEach(function(element) {
	element.onsubmit = function(event) {
		event.preventDefault();
		if (
			(!event.target.hasAttribute("data-form-validator")
				|| eval(event.target.getAttribute("data-form-validator")))
			&& (!event.target.hasAttribute("data-form-confirmation")
				|| confirm(event.target.getAttribute("data-form-confirmation")))
		) {
			// Get form data
			let data = new URLSearchParams();
			for (let pair of new FormData(event.target)) {
				let pairKey = pair[0];
				let pairValue = pair[1];
				data.append(pairKey, pairValue);
			}

			// Fetch data
			fetch(window.location.href, {
				method: 'post',
				body: data
			}).then(function(response) {
				response.json().then(function(json) {
					doActions(event.target, json);
				});
			});
		}
	};
});