import {athenaConfig, athenaConfigOptions} from '../../../global/athena-config.js';
import { athenaSpinner } from '../../renderer/athena-spinner.js';
import { athenaFetchApi } from '../../../global/athena-fetch-api.js';
import { handleResponseSearch } from './handle-response-search.js';
import checkActivePage from '../helpers/format-data-object.js';

/**
 * Fetch Search Data
 */
function fetchPagerData() {

    athenaConfigOptions.pagerContainer.addEventListener('click', function(event){
        let clickedElement = event.target.closest('.pager-item');
        if(clickedElement){

            let pager = clickedElement.getAttribute('data-value');
            if(pager){

                window.scrollTo({top: 0, behavior: 'smooth'});

                pager = JSON.parse(decodeURIComponent(pager));

                // Added spinner
                athenaConfigOptions.showSpinner = true;
                athenaSpinner();

                //Forming Data Object
                const data = {
                    'service': 'search/data',
                    'athenaUid': athenaConfigOptions.athenaUid,
                    'search': 0,
                    'q': athenaConfigOptions.searchQuery
                }

                if(athenaConfig.isCustomerLoyalty) {
                    data['customer_group_id'] = athenaConfigOptions.customerGroupID;
                }

                for (const queryKey in pager) {
                    data[queryKey] = pager[queryKey];
                }

                const {
                    isVisualSearch,
                    isCategory
                } = checkActivePage(data);

                isVisualSearch
                    .then(visual => {
                        if(athenaConfig.hybridSearchModel && !visual && !isCategory) {
                            data['hybrid_search_model_type'] = athenaConfig.hybridSearchModel;
                        }

                        athenaFetchApi(data)
                            .then(response =>
                                handleResponseSearch(
                                    response,
                                    false,
                                    visual,
                                    isCategory
                                )
                            );
                    });
            }

        }
    });

}

export {
    fetchPagerData
}