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 tabs = this.element;
        if (val) {
            check(val, false);
        }

        tabs.addEventListener('change', function(evn) {
            check(evn.target.value, true);
        })

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

            tabs.forEach(function(item) {
                if (item.value == id) {
                    item.selected = 'true';
                }
            });

            document.getElementById("specialist_search_order_by").value = index + '.asc';
                
            if (redirect) {
                document.querySelector('.submit-filter').click();
            }
        };
    }
}
