import { athenaConfigOptions } from '../../global/athena-config.js';
import { handleHtml } from '../../global/helpers/athena-global-helper.js';


/**
 * Append or Remove Active Filters
 *
 * @param filters
 * @param sorters
 */
function appendActiveFilters(
    filters,
    sorters
) {
    if(filters.length > 0) {
        athenaConfigOptions.activeFilterTitle?.classList.remove('hide-filter-title');
        athenaConfigOptions.activeFiltersContainer.innerHTML = '';

        filters.forEach((element, index) => {
            let urlParams = JSON.stringify(element.url_params);
            if(index === 1) {

                let urlParams;

                if(element.url_params['conversion-channel']){
                    urlParams = `{"q":"${element.url_params.q}", "conversion-channel": "${element.url_params['conversion-channel']}"}`;
                }else{
                    urlParams = `{"q":"${element.url_params.q}"}`;
                }


                if(sorters.length > 0){
                    sorters.forEach(function(sorter){
                        if(sorter.selected){
                            if(element.url_params['conversion-channel']){
                                urlParams = `{"q":"${element.url_params.q}","${sorter.option_key}":"${sorter.option_value}","conversion-channel": "${element.url_params['conversion-channel']}"}`
                            }else{
                                urlParams = `{"q":"${element.url_params.q}","${sorter.option_key}":"${sorter.option_value}"}`
                            }
                        }
                    });
                }

                athenaConfigOptions.activeFiltersContainer.prepend(
                    handleHtml(`
                        <span class="remove-all-filters active-filter-item" data-value="${encodeURIComponent(urlParams)}">
                            <span>Clear all</span>
                        </span>
                    `, `.remove-all-filters`)
                )
            }

            athenaConfigOptions.activeFiltersContainer.append(
                handleHtml(`
                    <span class="active-filter-item" data-value="${encodeURIComponent(urlParams)}">
                        <span>${element.name}</span>: 
                        <span>${element.label.replace(/%20/g, ' ')}</span>
                    </span>
                `, `.active-filter-item`)
            )
        })
    } else if(filters.length === 0) {
        athenaConfigOptions.activeFilterTitle?.classList.add('hide-filter-title');
        athenaConfigOptions.activeFiltersContainer.innerHTML = '';
    }
}

//Exporting all Functions
export {
    appendActiveFilters
}