<!--
 ~ Copyright 2022 youngmonkeys.org
 ~
 ~ Licensed under the ezyplatform, Version 1.0.0 (the "License");
 ~ you may not use this file except in compliance with the License.
 ~ You may obtain a copy of the License at
 ~
 ~     https://youngmonkeys.org/licenses/ezyplatform-1.0.0.txt
 ~
 ~ Unless required by applicable law or agreed to in writing, software
 ~ distributed under the License is distributed on an "AS IS" BASIS,
 ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ~ See the License for the specific language governing permissions and
 ~ limitations under the License.
-->

<!DOCTYPE html>
<html
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:th="http://www.thymeleaf.org">
<body>
<script th:fragment="scripts">
ezyadmin.createCombobox = function(comboboxName, comboboxClass) {
    $(document).ready(() => {
        $.widget( comboboxName || 'ezyadmin.combobox', {
            options: {
                dataFetcher: () => [],
                defaultValue: '',
                inputClasses: '',
                placeholder: ''
            },

            _create: function() {
                this.wrapper = $( "<span>" )
                    .addClass( comboboxClass || comboboxName || 'ezyadmin-combobox' )
                    .insertAfter( this.element );

                this.element.hide();
                this._createAutocomplete();
                this._createShowAllButton();
            },

            _createAutocomplete: function() {
                var value = "";
                if (this.options.defaultValue) {
                    this.element.val(this.options.defaultValue);
                }
                if (this.element.is("select")) {
                    var selected = this.element.children( ":selected" ),
                    value = selected.val() ? selected.text() : "";
                } else if (this.element.is("input")) {
                    value = this.element.val() || "";
                }
                this.input = $( "<input>" )
                    .appendTo( this.wrapper )
                    .val( value )
                    .attr( "value", value || "" )
                    .attr( "placeholder", this.options.placeholder || "" )
                    .addClass( `address-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left${this.options.inputClasses ? ` ${this.options.inputClasses}` : ''}` )
                    .autocomplete({
                        delay: 0,
                        minLength: 0,
                        source: this._source.bind( this ),
                        messages: {
                            noResults: "",
                            results: function() {}
                        }
                    })
                this.input.autocomplete("widget")
                    .parent()
                    .find(".ui-helper-hidden-accessible")
                    .remove();

                this._on( this.input, {
                    focus: function() {
                        this.input.autocomplete("search", "");
                    },
                    autocompleteselect: function( event, ui ) {
                        if (this.element.is("select")) {
                            if (ui.item.option) {
                                ui.item.option.selected = true;
                            }
                        } else if (this.element.is("input")) {
                            this.element.val(ui.item.value || ui.item.label);
                        }
                        this._trigger( "select", event, {
                            item: ui.item.option
                        });
                    },
                });
            },

            _createShowAllButton: function() {
                var input = this.input,
                    wasOpen = false;

                $( "<a>" )
                    .attr( "tabIndex", -1 )
                    .appendTo( this.wrapper )
                    .button({
                        icon: "ui-icon-triangle-1-s",
                        showLabel: false
                    })
                    .removeClass( "ui-corner-all" )
                    .addClass( "address-combobox-toggle ui-corner-right" )
                    .on( "mousedown", function() {
                        wasOpen = input.autocomplete( "widget" ).is( ":visible" );
                    })
                    .on( "click", function() {
                        input.trigger( "focus" );
                        if (wasOpen) {
                            return;
                        }
                        input.autocomplete( "search", "" );
                    });
            },

            _stripAccents: function (s) {
                if (!s) {
                    return "";
                };
                if (this.options.stripAccents) {
                    return this.options.stripAccents(s);
                }
                return s
                  .normalize("NFD")
                  .replace(/[\u0300-\u036f]/g, "")
                  .replace(/đ/g, "d")
                  .replace(/Đ/g, "D");
             },

            _source: async function (request, response) {
                var term = this._stripAccents(request.term).toLowerCase();
                var data = await Promise.resolve(
                    this.options.dataFetcher(term)
                );
                data = data || [];
                var results = $.map(data, (item) => {
                    var label = item.label || item.toString();
                    var value = item.value || label;
                    var norm = this._stripAccents(label).toLowerCase();

                    if (!term || norm.indexOf(term) !== -1) {
                        return { label: label, value: value, data: item };
                    }
                });
                response(results);
            },

            _destroy: function() {
                this.wrapper.remove();
                this.element.show();
            }
        });
    });
}
</script>
</body>
</html>
