/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/* eslint-env browser */

const SyliusAddToCart = (el) => {
    const url = el.getAttribute('action');
    const {redirect} = el.dataset;
    const validationElement = el.querySelector('#sylius-cart-validation-error');
    const addToCartBtn = el.querySelector('.btn-add-cart');

    el.addEventListener('submit', (e) => {
        e.preventDefault();

        const formData = new FormData(e.target);

        fetch(url, {method: 'POST', body: formData})
            .then((response) => {
                if (String(response.status).match(/^2.*/)) {
                    validationElement.classList.add('d-none');
                    if (addToCartBtn !== null) {
                        addToCartBtn.classList.remove('load');
                        addToCartBtn.setAttribute('type', 'submit');
                    }

                    if (redirect) {
                        window.location.href = redirect;
                    }

                    return {};
                }

                return response.json();
            })
            .then((data) => {
                if (!data.errors) {
                    return;
                }

                validationElement.classList.remove('d-none');
                let validationMessage = '';

                Object.entries(data.errors.errors).forEach(([, message]) => {
                    validationMessage += message;
                });

                validationElement.innerHTML = validationMessage;
                el.classList.remove('loading');
                if (addToCartBtn !== null) {
                    addToCartBtn.classList.remove('load');
                    addToCartBtn.setAttribute('type', 'submit');
                }
            });
    });
};

export default SyliusAddToCart;
