import { athenaFetchApi } from './athena-fetch-api.js';
import { athenaConfig, athenaConfigOptions } from './athena-config.js';

export default function populateConfig(isSPA) {
    function fetchConfig()
    {
        athenaFetchApi({
            'service': 'configuration'
        })
            .then(response => {
                const {
                    autocompleteLayoutType,
                    productDomSelector,
                    currencyPosition,
                    currency,
                    infiniteScrollStatus,
                    pagerStatus,
                    decimals,
                    decimalPoint,
                    separator,
                    voiceSearchStatus,
                    voiceSearchLanguage,
                    hybridSearchModelType
                } = response.data.configurations;

                athenaConfig.pagerStatus = pagerStatus;
                athenaConfig.InfiniteScrollStatus = infiniteScrollStatus;
                athenaConfig.priceRangePlacement = currencyPosition;
                athenaConfig.decimals = decimals;
                athenaConfig.decimalPoint = decimalPoint;
                athenaConfig.separator = separator;
                athenaConfig.priceRangeUnit = currency.replace('_', ' ');
                athenaConfig.layoutType = autocompleteLayoutType;
                athenaConfigOptions.productDomSelectors.autocomplete = productDomSelector;

                if(
                    voiceSearchStatus || typeof voiceSearchStatus !== 'undefined' &&
                    voiceSearchLanguage || typeof voiceSearchLanguage !== 'undefined'
                ) {
                    athenaConfig.voiceSearchStatus = voiceSearchStatus;
                    athenaConfig.voiceSearchLang = voiceSearchLanguage;
                }

                if(hybridSearchModelType || typeof hybridSearchModelType !== 'undefined')
                    athenaConfig.hybridSearchModel = hybridSearchModelType;

                const event = new Event('finishedConfiguration');
                window.dispatchEvent(event);
            });
    }

    isSPA ?
        document.addEventListener('SPAContentLoaded', () => fetchConfig()) :
        document.addEventListener('DOMContentLoaded', () => fetchConfig());
}