function clear_foreign_key_field(uuid_field, dflex_container) {
    dflex_container.innerHTML = '';
    var span = document.createElement('span');
    span.setAttribute('class', 'text-secondary');
    span.appendChild(document.createTextNode('None selected'));
    dflex_container.appendChild(span);
    uuid_field.removeAttribute('value')
}

function initialize_autocompletion_foreign_key_field(search_element) {
    var image_field_name = search_element.getAttribute('data-ac-image-field');
    var name_field_name = search_element.getAttribute('data-ac-name-field');
    var search_url = search_element.getAttribute('data-ac-url');
    var base_id = search_element.getAttribute('id');
    var uuid_field = search_element.parentElement.parentElement.querySelector('#'+base_id+'-uuid-field');
    var dflex_container = search_element.parentElement.parentElement.querySelector('#'+base_id+'-dflex-container');
    var initial_delete_button = search_element.parentElement.parentElement.querySelector('[data-ac-delete]');

    console.log(initial_delete_button);
    console.log(image_field_name);
    console.log(search_url);
    console.log(base_id);
    
    if (initial_delete_button) {
        initial_delete_button.addEventListener('click', (e) => {
            clear_foreign_key_field(uuid_field, dflex_container);
        });
    }

    // select first match if any on enter
    search_element.addEventListener('keydown', (e) => {
        if (e.key === "Enter") {
            e.preventDefault();
            first_search_result = search_element.parentElement.querySelector('li')
            if (first_search_result) {
                first_search_result.click()
            }
        }
    });

    new AutocompleteCustomUi(
        base_id, base_id+'-ac-ul', function(search_query, autocomplete_obj) {
            api_ajax_request_without_send('GET', search_url+`?search=${encodeURIComponent(search_query)}`, function(method, url, json) {
                if (json.results == undefined || json.results == null)
                    return;
                var results = json.results;
                var nodes = [];

                if (image_field_name != '' && image_field_name != null) {
                    for (var i = 0; i < results.length; i++) {
                        var res = results[i];
                        var node = AutocompleteCustomUi.create_media_div(res[image_field_name], [document.createTextNode(res[name_field_name])]);
                        nodes.push({'ui': node, 'data': {'result': res, 'uuid_field': uuid_field}});
                    }
                } else {
                    for (var i = 0; i < results.length; i++) {
                        nodes.push({'ui': document.createTextNode(results[i][name_field_name]), 'data': {'result':results[i], 'uuid_field': uuid_field}})
                    }
                }

                autocomplete_obj.show_results(nodes, function(data) {
                    var name = data['result'][name_field_name];
                    if (image_field_name != '' && image_field_name != null) {
                        var image = data['result'][image_field_name];
                        if (image == null) {
                            image = fallback_img_path;
                        }
                        dflex_content = AutocompleteCustomUi.create_media_div(image, [document.createTextNode(name)]);
                    } else {
                        dflex_content = document.createTextNode(name);
                    }
                    dflex_container.innerHTML = '';
                    dflex_container.appendChild(dflex_content);
                    
                    search_element.value = data['result'][name_field_name];
                    data['uuid_field'].value = data['result'].id;
                    
                    var span = document.createElement('span');
                    span.setAttribute('class', 'btn-close ms-4');
                    span.addEventListener('click', (e) => {
                        clear_foreign_key_field(uuid_field, dflex_container);
                        search_element.value = '';
                    });
                    dflex_container.appendChild(span);

                })
            }, function (){});
        }
    )
}


function initialize_autocompletion_for_foreign_key_fields() {
    var autocomplete_searches = document.querySelectorAll("[data-ac-url]");
    if (autocomplete_searches.length == 0) {
        return;
    }
    autocomplete_searches.forEach(initialize_autocompletion_foreign_key_field);
}


document.addEventListener("DOMContentLoaded", function(event) { 
    initialize_autocompletion_for_foreign_key_fields();
});