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

/**
 * Fetch Queried Data
 *
 * @param query
 */
function fetchPriceRangeData(query) {

    athenaConfigOptions.scrollStatus = false;

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

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

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

    //Handle Url for Showing
    let filteredUrl = window.location.href.split('&')[0];
    query = query.split('&');

    //Get URL Search params and add it to data
    const queries = getUrlSearchParams(query);
    for (const queryKey in queries) {
        data[queryKey] = queries[queryKey];
        if(queryKey !== 'q' || queryKey !== 'image') filteredUrl += `&${queryKey}=${queries[queryKey]}`;
    }

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

    window.history.pushState("", "", filteredUrl);

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