/* eslint-disable */
import { onPageLoadComplete } from '@nimius/event-utility';

function desklineFormSubmit(e) {
    e.preventDefault();

    // get values from form
    const
        form = document.querySelector('[data-feratel-quicksearch]'),
        targetUri = form.getAttribute('data-target-uri'),
        localStorageId = form.getAttribute('data-local-storage-id'),
        dateFrom = document.querySelector('[data-feratel-quicksearch\\.date-from]').value.split('.'),
        dateTo = document.querySelector('[data-feratel-quicksearch\\.date-to]').value.split('.'),
        numberAdults = document.querySelector('[data-feratel-quicksearch\\.adults]').value,
        numberChildren = document.querySelector('[data-feratel-quicksearch\\.children]').value,
        childArray = [];

    if (numberChildren > 0) {
        if (numberChildren > 0) {
            for (let i = 1; i <= numberChildren; i++) {
                let ageValue = document.querySelector(`[data-feratel-quicksearch\\.age-child-${i}]`).value;

                if (ageValue !== "" && !isNaN(ageValue)) {
                    childArray.push(Number(ageValue));  // Convert to number and add to the array
                } else {
                    childArray.push(0);  // Convert default value "-" to 0 and add to the array
                }
            }
        }
    }

    if (localStorageId && dateFrom && dateTo && numberAdults) {
        dw.accommodationQuickFind(
            localStorageId,

            {
                dateFrom: new Date(dateFrom[2] + '-' + dateFrom[1] + '-' + dateFrom[0]),
                dateTo: new Date(dateTo[2] + '-' + dateTo[1] + '-' + dateTo[0]),
                occupancy1: {
                    units: 1,
                    adults: numberAdults,
                    children: childArray,
                }
            },

            function() {
                window.location.href = targetUri
            })

        return false;
    }
}

onPageLoadComplete(async () => {
    const form = document.querySelector('[data-feratel-quicksearch]');

    if (form) {
        form.addEventListener("submit", desklineFormSubmit);
    }
});

/* eslint-enable */
