import {
    setAthenaUid,
    getCookie,
    isSearchPageActive
} from '../global/helpers/athena-global-helper.js';
import { athenaConfigOptions } from '../global/athena-config.js';
import { fetchInitialData } from './ajax/search/fetch-initial-data.js';
import { infiniteScroll } from './infinite-scroll/infinite-scroll.js';
import { fetchFilteredData } from './ajax/search/fetch-filtered-data.js';
import { fetchSortedData } from './ajax/search/fetch-sorted-data.js';
import { fetchPagerData } from './ajax/search/fetch-pager.js';
import { fetchProductsPerPage } from './ajax/search/fetch-products-per-page.js';
import lazyLoad from '../global/helpers/lazy-loading.js';

export default function search(isSPA)
{
    if(isSearchPageActive()) {
        function initiateSearch()
        {
            //Get or Set Athena UID
            athenaConfigOptions.athenaUid = localStorage.getItem('_athena-uid') ? localStorage.getItem('_athena-uid') : setAthenaUid();
            //Get Athena Customer Cookie
            athenaConfigOptions.customerCookie = getCookie('athena_customer_cookie');
            //Adding Suffix Area
            athenaConfigOptions.suffixArea = 'search';
            // Get Init Data
            fetchInitialData();
            // Filters
            fetchFilteredData();
            // Pager
            fetchPagerData();
            // Infinite Scroll
            infiniteScroll();
            //Lazy Loading Images
            lazyLoad('.athena-product-image-photo', true);
        }

        window.addEventListener('sorter-ready', () => {
            fetchSortedData();
        });

        window.addEventListener('products-per-page-ready', () => {
            fetchProductsPerPage();
        });

        isSPA ?
            document.addEventListener('SPAContentLoaded', () => {
                window.addEventListener('finishedConfiguration', () => {
                    initiateSearch();
                });
            }) :
            document.addEventListener('DOMContentLoaded', () => {
                window.addEventListener('finishedConfiguration', () => {
                    initiateSearch();
                });
            });
    }
}
