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

/**
 * Append Sorters
 *
 * @param sorters
 * @param products
 */
function appendSearchSorters(sorters, products) {
    athenaConfigOptions.searchToolbarContainer.innerHTML = '';
    if(sorters.length && products.length){

        athenaConfigOptions.searchToolbarContainer.append(
            handleHtml(`
                  <div class="athena-search-sorter-parent">
                      <span class="athena-search-sorter__sort-by">Sort by</span>
                      <select class="athena-search-sorter"></select>
                  </div>
            `, '.athena-search-sorter-parent')
        );

        let sorterElement = document.querySelector('.athena-search-sorter');
        sorters.forEach((item, key) => {
            const urlParams = encodeURIComponent(JSON.stringify(item.url_params));
            sorterElement.append(
                handleHtml(`
                      <option class="athena-search-sorter-option" value="${urlParams !== 'undefined' && urlParams}" ${item.selected ? `selected="${item.selected}"` : ''}>${item.option_label}</option>
                `, '.athena-search-sorter-option')
            )
        });


        let sorterEvent = new Event('sorter-ready');
        window.dispatchEvent(sorterEvent);
    }
}


//Exporting all Functions
export {
    appendSearchSorters
}