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 Products Per page
 */
function fetchProductsPerPage() {

    let prodPerPage = document.querySelector('.products-per-page');
    prodPerPage.addEventListener('change', function () {
        athenaConfigOptions.scrollStatus = false;

        let prodPerPage = this.value;
        prodPerPage = JSON.parse(decodeURIComponent(prodPerPage));

        athenaConfigOptions.showSpinner = true;
        athenaSpinner();

        const data = {
            'service': 'search/data',
            'athenaUid': athenaConfigOptions.athenaUid,
            'search': 0,
            'page': 1,
            'q': athenaConfigOptions.searchQuery
        }

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

        for (const queryKey in prodPerPage) {
            if(queryKey !== 'page') {
                data[queryKey] = prodPerPage[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 {
    fetchProductsPerPage
}