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 Sorted Data
 */
function fetchSortedData() {

    let sorter = document.querySelector('.athena-search-sorter');
    sorter.addEventListener('change', function(event){
        athenaConfigOptions.scrollStatus = false;

        let sorter = this.value;
        sorter = JSON.parse(decodeURIComponent(sorter));
            
        // Added spinner
        athenaConfigOptions.showSpinner = true;
        athenaSpinner();

        //Forming Data Object
        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 sorter) {
            if(queryKey !== 'page') {
                data[queryKey] = sorter[queryKey];
            }
        }

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

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

        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 {
    fetchSortedData
}