angular.module('autocompleteInputDirective', [])
    .directive('autocompleteInput', ['$http', function ($http) {
        return {
            restrict: 'A',
            replace: true,
            template: `<span>
                         <input name="autocompleteInput" class="display-block" placeholder="{{placeholder}}" type="text" value="{{ngModel}}" ng-model="ngModel" ng-change="autoCompleteFn()"/>
                         <ul class="dropdown-menu autocomplete-suggestions display-block" ng-if="suggestions.length > 0">
                           <li ng-repeat="item in suggestions track by $index" ng-click="selectSuggestion(item.id)">
                             <a ng-bind-html="item.label"></a>
                           </li>
                         </ul>
                       </span>`,
            scope: {
                ngModel: '='
            },
            link: function (scope, element, attrs) {
                scope.suggestions = [];
                scope.placeholder = attrs.placeholder;
                scope.autoCompleteFn = function () {
                    $http.get(`${attrs.url}?text=${scope.ngModel}`).then(
                        function (result) {
                            $('.autocomplete-suggestions').addClass('display-block');
                            scope.suggestions = [];
                            for (const item of result.data) {
                                const label = item.replace(scope.ngModel, '<span class="bold">' + scope.ngModel + '</span>')
                                scope.suggestions.push({id: item, label: label});
                            }
                        },
                        function (error) {
                            notify.error(error.data);
                            common.globalSpinner.hide();
                        });
                }

                // hide suggestions in case of click outside of the element
                document.addEventListener('click', () => {
                    let autocomplete = $('.autocomplete-suggestions');
                    if (autocomplete.is(":visible")) {
                        autocomplete.removeClass('display-block');
                    }
                });

                scope.selectSuggestion = function (value) {
                    scope.ngModel = value;
                    scope.suggestions = [];
                }
            }
        };
    }]);
