import { athenaConfig, athenaConfigOptions } from '../../../global/athena-config.js';
import { athenaSpinner } from '../../renderer/athena-spinner.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 { detectSpecialCharacters } from '../../../global/helpers/athena-global-helper.js';
import checkActivePage from '../helpers/format-data-object.js';

/**
 * Fetch Search Data
 */
function fetchInitialData() {
    // Added spinner
    athenaConfigOptions.showSpinner = true;
    athenaSpinner();

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

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

    //Get URL Search params and add it to data
    const queries = getUrlSearchParams();

    let noQueries = false;
    for (const queryKey in queries) {
        if(typeof queries[queryKey] === 'undefined' || !queries[queryKey]) {
            noQueries = true;
        }
    }

    for (const queryKey in queries) {
        if(queryKey !== 'filter') {
            data[queryKey] = queries[queryKey].replace(/%20/g, ' ');
        }
    }

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

    const specialCharProperties = ['q', 'image', 'category', 'level'];
    const hasSpecialChars = specialCharProperties.some(prop =>
        data.hasOwnProperty(prop) && detectSpecialCharacters(data[prop])
    );

    if (hasSpecialChars) {
        athenaConfigOptions.showSpinner = false;
        athenaSpinner();
        window.history.go(-1);
        return;
    }

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

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

export {
    fetchInitialData
}