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

    $.fn.djangoAdminSelect2 = function() {
        $.each(this, function(i, element) {
            const select2_config = {};
            let filtered_by_fields;
            let reset_on_something = false;
            const reset_on_excluded = [];
            const reset_on_included = [];
        
            if (element.dataset.hasOwnProperty('drilldown_enabled')) {
                    
                if (element.dataset.hasOwnProperty('reset_on_included')) {
                    reset_on_included.push(...JSON.parse(element.dataset.reset_on_included));
                    reset_on_something = true;
                }

                if (element.dataset.hasOwnProperty('filtered_by')) {
                    filtered_by_fields = JSON.parse(element.dataset.filtered_by);
                    if (element.dataset.hasOwnProperty('reset_on_excluded')) {
                        reset_on_excluded.push(...JSON.parse(element.dataset.reset_on_excluded));
                        reset_on_something = true;
                    }
    
                }
                if (reset_on_something) {
                    element.drilldown_items = {};
                }

                select2_config.templateResult = (item, container)=>{
                    let styleClass = '';

                    element.classList.add('drilldown');

                    if (item.ddok === 1) {
                        styleClass = 'drilldown_ok';
                    } else {
                        styleClass = 'drilldown_ko';
                    }

                    container.classList.add(styleClass);
                    if (reset_on_something) {
                        element.drilldown_items[item.id] = item;
                    }

                    if (item.hasOwnProperty('autoselect')) {
                        const includedOnly = element.dataset.included_only ?? false;
                        const dataLength = $(element).select2('data').length;

                        if (includedOnly || dataLength == 0) {
                            $(element).select2("trigger", "select", {
                                data: item
                            })
                        }
                    }

                    return $(`<span class="${styleClass}"></span>`).text(item.text);
                }                
            }
            
            select2_config.ajax = {
                data: (params)=>{
                    const {fieldName, appLabel, modelName} = element.dataset;
                    const out = {
                        term: params.term,
                        page: params.page,
                        app_label: appLabel,
                        model_name: modelName,
                        field_name: fieldName
                    };

                    if (element.dataset.hasOwnProperty('drilldown_enabled')) {

                        if (reset_on_something && (params.page ?? 1) < 2) {
                            element.drilldown_items = {};
                        }

                        if (element.dataset.hasOwnProperty('filtered_by')) {
                            
                            const filtered_by_dict = {};
                            let some_obj = false;

                            for (let i in filtered_by_fields) {
                                if (filtered_by_fields.hasOwnProperty(i)) {
                                    const filtering_field = filtered_by_fields[i];
                                    const field_id = element.dataset.select2Id;
                                    const filtering_field_id = `${field_id.slice(0, field_id.length - fieldName.length)}${filtering_field}`;
                                    const filtering_value = document.querySelector(`[data-select2-id="${filtering_field_id}"].admin-autocomplete`).value;

                                    if (filtering_value !== '') {
                                        filtered_by_dict[filtering_field] = filtering_value;
                                        some_obj = true;
                                    }
                                }
                            }

                            if (some_obj) {
                                out.filtered_by_dict = JSON.stringify(filtered_by_dict);
                            }
                        }
                    }

                    return out;
                }
            };

            $(element).select2(select2_config);

            if (reset_on_something) {
                $(element).on('select2:select', (ev) => {
                    const data = $(element).select2('data');

                    if (element.hasOwnProperty("drilldown_items") && Array.isArray(data) && data.length > 0) {
                        const item = element.drilldown_items[data[0].id];
                        const ddok = item !== undefined ? item.ddok : undefined;

                        if (ddok !== undefined) {
                            let all_fields_to_reset = ddok ? reset_on_included : reset_on_excluded;

                            if (all_fields_to_reset.length > 0) {
                                all_fields_to_reset.forEach((field_to_reset)=>{
                                    const field_name = element.dataset.fieldName;
                                    const field_id = element.dataset.select2Id;
                                    const id_to_reset = `${field_id.slice(0, field_id.length - field_name.length)}${field_to_reset}`;
                                    const element_to_reset = document.querySelector(`#${id_to_reset}.admin-autocomplete`);
                                    $(element_to_reset).val(null).trigger('change');
                                }
                                );
                            }
                        }
                    }
                }
                );
            }
        });
        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();
    }
    );
}
