$(document).ready(function () {
    selectpickerAPI();
    enableSelectClear();
});

function setStatements($element, statements) {
    if (!statements) statements = "";

    $element.val(statements.split(","));
    $element.selectpicker('refresh');
}

function getDocTexts(url, $valueElement, $displayElement, doctype) {
    $.get(url + "?docType=" + doctype, function (data) {
        var ids = [];
        if (data.length > 0) {
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].Id);
            }
        }
        
        $valueElement.val(ids.join(","));
        setStatements($displayElement, $valueElement.val());
    });
}

// To use API with selectpicker add class selectpickerAPI to select element
// Set attributes data-live-search="true" and provide API route for data-api-url

function selectpickerAPI() {
    $(".selectpickerAPI").each(function () {
        $(this).selectpicker({
            noneResultsText: $("#Searching").val()
        });
    });

    let timer = null
    $('select').on('loaded.bs.select', function () {
        $(".bootstrap-select .bs-searchbox input").on('keyup', function () {
            clearTimeout(timer);
            timer = setTimeout(getDropdownData, 600)
            let selectElem = $(this).closest("div.dropdown-menu").siblings("select")
            let apiUrl = selectElem.data("api-url");
            let multiple = selectElem.attr("multiple") == "multiple";
            let searchTerm = $(this).val();

            function getDropdownData() {
                if (apiUrl) {
                    $.ajax({
                        url: apiUrl,
                        data: {
                            searchTerm: searchTerm
                        },
                        success: function (data) {
                            var res = $.map(JSON.parse(data), function (item, index) {
                                return {
                                    id: item[Object.keys(item)[0]],
                                    text: item[Object.keys(item)[1]]
                                };
                            })

                            if (res.length == 0) {
                                $(".dropdown-menu .no-results").text($("#NoResultFound").val());
                            }

                            $(selectElem).find("option").remove()
                            if (!searchTerm && !multiple) {
                                $(selectElem).append("<option></option>")
                            }

                            $.each(res, function (index, item) {
                                $(selectElem).append($("<option>", {
                                    value: item.id,
                                    text: item.text
                                }));
                            })

                            $(selectElem).selectpicker("refresh");
                        }
                    });
                }
            }
        });
    });
}

function enableSelectClear() {
    // Add the class clear-select to the <select> element to enable clearing selected options for both multiple and single select pickers.
    // The select picker will be cleared when the first option is clicked. 
    // Set the first option to an empty value or Loc.ShowAll, for example, to enable this functionality.
    $('.clear-select').on('changed.bs.select', function (e, clickedIndex) {
        if (clickedIndex === 0) {
            $(this).selectpicker('deselectAll');
        }
    });
}