/**
 * Adding Observer to Products
 * to follow on what page are you currently scrolled
 *
 * @param currentPage
 */
function addObserverToProducts(currentPage) {
    const appendedElement = document.querySelectorAll(`[data-page="${currentPage}"]`);

    //Forming URL
    let href = window.location.href;
    let finalUrl = '';
    if(href.includes('page=')) {
        href = href.split('&');
        href.forEach((urlParam, index) => {
            if(index === 0) {
                finalUrl += urlParam;
            } else if(!urlParam.includes('page')) {
                finalUrl += `&${urlParam}`;
            }
        });
    } else {
        finalUrl = href;
    }

    //Adding Observer
    const observer = new IntersectionObserver((entries) => {
        const entry = entries[0];

        if(entry.isIntersecting) {
            const page = appendedElement[0].getAttribute('data-page');
            window.history.pushState("", "", page > 1 ? `${finalUrl}&page=${page}` : `${finalUrl}`);
        }

    }, {
        rootMargin: '',
        threshold: 0
    });

    if(appendedElement.length) {
        appendedElement.forEach(function(element, index){
            observer.observe(element);
        });
    }
}

//Exporting all Functions
export {
    addObserverToProducts
}