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 fetchFilteredData() {
    athenaConfigOptions.athenaSidebar.addEventListener('click', (event) => {
        const clickedElement = event.target.closest('.athena-filter-item');
        if(clickedElement) getData(clickedElement);
    });

    athenaConfigOptions.activeFiltersContainer.addEventListener('click', (event) => {
        const clickedElement = event.target.closest('.active-filter-item');
        if(clickedElement) getData(clickedElement);
    });

    athenaConfigOptions.visualFilters.addEventListener('click', (event) => {
        const clickedElement = event.target.closest('.visual-filter-image');
        if(clickedElement) getData(clickedElement);
    });
}

function getData(clickedElement){
    athenaConfigOptions.scrollStatus = false;
    let filter = clickedElement.getAttribute('data-value');
    filter = JSON.parse(decodeURIComponent(filter));

    // 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 filter) {
        if(queryKey !== 'page') {
            data[queryKey] = filter[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 {
    fetchFilteredData
}