import { Controller } from 'stimulus';

/*
 * This is an example Stimulus controller!
 *
 * Any element with a data-controller="searchOrderByInput" attribute will cause
 * this controller to be executed. The name "searchOrderByInput" comes from the filename:
 * searchOrderByInput_controller.js -> "searchOrderByInput"
 *
 * Delete this file or adapt it for your use!
 */
export default class extends Controller {
    connect() {
        var val = document.getElementById("specialist_search_order_by").value;
        var items = this.element.querySelectorAll('span');
        
        if (val) {
            check(val, false);
        }

        items.forEach(function(el) {
            el.addEventListener('click', function(evn) {
                check(evn.target.id, true);
            });
        })

        function check(index, redirect) {
            console.log(index)
            var array = index.split('.');
            var id = array[0];
            var sort = array[1];

            items.forEach(function(item) {
                var iconASC = item.querySelector('.fa-sort-amount-asc');
                var iconDESC = item.querySelector('.fa-sort-amount-desc');
                
                item.classList.remove('sort-line__item--active');

                if (id == item.id) {
                    item.classList.add('sort-line__item--active');

                    if (sort == 'desc') {
                        item.classList.remove('asc');
                    }

                    if (item.classList.contains('asc')) {
                        iconASC.classList.remove('d-none');
                        iconDESC.classList.add('d-none');
                        item.classList.remove('asc');
                        document.getElementById("specialist_search_order_by").value = item.id + '.asc';
                        
                        if (redirect) {
                            document.querySelector('.submit-filter').click();
                        }
                    } else {
                        iconDESC.classList.remove('d-none');
                        iconASC.classList.add('d-none');
                        item.classList.add('asc');
                        document.getElementById("specialist_search_order_by").value = item.id + '.desc';
                        
                        if (redirect) {
                            document.querySelector('.submit-filter').click();
                        }
                    }
                } else {
                    iconDESC.classList.add('d-none');
                    iconASC.classList.add('d-none');
                    item.classList.add('asc');
                }
            });
        };
    }
}
