'use strict';
{
    const $ = django.jQuery;

    $.fn.djangoAdminSelect2 = function() {
        $.each(this, function(i, element) {
            var select2_config = {};
            select2_config.ajax = {
                data: (params)=>{
                    var field_name = element.dataset.fieldName
                    var out = {
                        term: params.term,
                        page: params.page,
                        app_label: element.dataset.appLabel,
                        model_name: element.dataset.modelName,
                        field_name: field_name
                    };
                    if (element.dataset.hasOwnProperty('linkedfields')) {
                        out.drilldown = 1;
                        var linkedfields = JSON.parse(element.dataset.linkedfields)
                        var linkedfields_obj = {};
                        var some_obj = false;
                        for (var i in linkedfields) {
                            if (linkedfields.hasOwnProperty(i)) {
                                var remote_field = linkedfields[i];
                                var field_id = element.dataset.select2Id;
                                var remote_id = field_id.slice(0, field_id.length - field_name.length) + remote_field;
                                var value = document.querySelectorAll('[data-select2-id=' + remote_id + '].admin-autocomplete')[0].value;
                                if (value !== '') {
                                    linkedfields_obj[remote_field] = value;
                                    some_obj = true;
                                }
                            }
                        }
                        if (some_obj) {
                            out['linkedfields'] = JSON.stringify(linkedfields_obj);
                        }
                    }
                    return out
                }
            };
            if (element.dataset.hasOwnProperty('linkedfields')) {
                select2_config.templateResult = (item,container)=>{
                    var styleClass = '';

                    element.classList.add('drilldown');
                    if (item.ddok === 1) {
                        styleClass = 'drilldown_ok';
                    } else {
                        styleClass = 'drilldown_ko';
                    }
                    container.classList.add(styleClass);
                    if (item.hasOwnProperty('autoselect')) {
                        if ((element.dataset.included_only ?? false) || $(element).select2('data').length == 0) {
                            $(element).select2("trigger", "select", {
                                data: item
                            })
                        }
                    }

                    return $('<span class="' + styleClass + '"></span>').text(item.text);
                }
            }
            $(element).select2(select2_config);
        });
        return this;
    }
    ;

    $(function() {
        // Initialize all autocomplete widgets except the one in the template
        // form used when a new formset is added.
        $('.admin-autocomplete').not('[name*=__prefix__]').djangoAdminSelect2();
    });

    document.addEventListener('formset:added', (event)=>{
        $(event.target).find('.admin-autocomplete').djangoAdminSelect2();
    }
    );
}
