(function () {
    'use strict';

    angular
        .module('editorRotas')
        .directive('autoCompleteComboBox', autoCompleteComboBox);


    autoCompleteComboBox.$inject = ['__env'];

    /* @ngInject */
    function autoCompleteComboBox(__env) {
        const directive = {
            link: link,
            restrict: 'A',
            require: 'ngModel',
            scope: false
        };

        let _dataList = [];
        let _element;
        let _wasOpen;
        let _wrapper;
        let _attr;
        let _parentHasClass;
        let _widget;

        function link(scope, element, attr, ctrl) {
            _dataList = JSON.parse(attr.list);
            _element = element;
            _attr = attr;

            $.widget("custom.combobox", {
                _create: _create
            });

            $(element).combobox();
        }

        function _create() {
            _widget = this;
            _wrapper = $('#nome-setor').parent();
            _parentHasClass = _wrapper.hasClass('custom-combobox');
            if (!_parentHasClass)
                _wrapper = $("<span>")
                    .addClass("custom-combobox")
                    .insertAfter(_element);

            _createAutocomplete();
        }

        function _createAutocomplete() {
            const selected = _element.children(":selected");
            const value = selected.val() ? selected.text() : "";

            _buildInput(value)

            $('.ui-autocomplete').addClass(`autocompletecombobox`);
        }

        function _source(request, response) {
            const matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
            const result = _dataList.filter(dataItem => {
                return !request.term || matcher.test(dataItem[_attr.label]);
            }).map((dataItem) => {
                const label = `${dataItem[_attr.label]} - ${dataItem[_attr.sublabel]}`;
                return {
                    label: label,
                    value: label,
                    option: dataItem[_attr.option]
                };
            });

            response(result);
        }

        function _buildInput(value) {
            const element = _parentHasClass ? _element : _element.appendTo(_wrapper);
            element
                .val(value)
                .addClass("custom-combobox-input ui-state-default ui-corner-left")
                .autocomplete({
                    delay: 0,
                    minLength: 0,
                    source: _source
                })
                .tooltip({
                    classes: {
                        "ui-tooltip": "ui-state-highlight"
                    }
                }).on('mousedown', function () {
                    _wasOpen = $(this).autocomplete('widget').is(':visible');
                })
                .on('click', function () {

                    if (_wasOpen) {
                        return;
                    }

                    $(this).autocomplete('search', $(this).val());
                });

            _widget._on(_element, {
                autocompleteselect: function (event, ui) {
                   _element.attr('data-value', ui.item.option);
                   _element.val(ui.item.option);
                   _element.trigger('input');
                }
            });
        }

        return directive;
    }
})();
