let pollDiv = $(".poll-select-two");

pollDiv.select2({
    ajax: {
        url: mpPanelBaseUrl + "/poll-request",
        type: "post",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                search: $.trim(params.term)
            };
        },
        processResults: function (data) {
            return {
                results: data
            };
        },
        cache: true
    },
    language: {
        inputTooShort: function () {
            return "جستجو در نظرسنجی‌ها";
        },
        noResults: function () {
            return "جستجو نتیجه‌ای نداشت";
        }
    },
    dir: "rtl",
    minimumInputLength: 0,
    templateResult: formatPoll,
    templateSelection: formatPollSelection
});


let pollClearBtn = pollDiv.parent().find('.clear-s2');

pollDiv.on("change",function(e){
    let selectedValue = pollDiv.val();
    if(selectedValue == null || selectedValue == 0 || selectedValue == "" ){
        pollClearBtn.hide();
    }else{
        pollClearBtn.show();
    }
});

pollClearBtn.click(function(){
    pollDiv.val(0);
    pollDiv.trigger('change');
});


function formatPoll(cat) {
    if (cat.loading) {
        return cat.text;
    }
    let $container = $(
        "<div class='select2-result clearfix'>" +
        "<div class='select2-result-id'></div>" +
        "<div class='select2-result-meta'>" +
        "<div style='display:block'><div class='select2-result-text'></div></div>" +
        "<div class='select2-result-summary'></div>" +
        "</div>" +
        "</div>"
    );

    $container.find(".select2-result-id").text(cat.id);
    $container.find(".select2-result-text").text(cat.text);
    $container.find(".select2-result-summary").text(cat.question);

    return $container;
}

function formatPollSelection(cat) {
    return cat.text;
}