'use strict';

angular.module('ui.IR', [])
  .directive('irwidget', ['$injector',
    function ($injector) {
      return {
        scope: {
          disabled: '=',
          deact: '=',
          institution: '=',
          name: '@',
        },
        require: 'ngModel',
        restrict: 'E',
        replace: 'true',
        template: "<input class=\"form-control\" type=\"text\" value=\"\" ng-disabled=\"deact\" />",
        link: function (scope, element, attrs, modelCtrl) {
          scope.deact = scope.disabled === true ? true : false;

          if ($injector.has('wbEntitiesSvc')) {
            var wbEntitiesSvc = $injector.get('wbEntitiesSvc');

            if (attrs.name == 'institutionID') {
              scope.deact = true;
            } else {
              element.addClass('with-searchable-icon');
              element.after("<i class='glyphicon glyphicon-search searchable-mark' onmousedown='return false;'></i>");
              element.attr('autocomplete', '');

              var institutions = [];

              element.on('focus', function () {
                element.autocomplete({
                  appendTo: element.parent(),
                  source: function (request, response) {
                    wbEntitiesSvc.Search("organisation", null, request.term)
                      .then(function (autocompleteResults) {
                        institutions = autocompleteResults;
                        response($.map(autocompleteResults, function (value) {
                          return {
                            //label: value.acronym + ', ' + value.name + ', ' + value.countryCode,
                            //value: value.acronym + ', ' + value.name + ', ' + value.countryCode,
                            //id: value.countryCode + ":" + value.id
                        	label: value.acronym + ', ' + value.name + ', ' + value.countryCode,
                            value: value.name,
                            id: value.id
                          };
                        }));
                      }, function (error) {
                      });
                  },
                  select: function (event, ui) {
                    this.value = ui.item.label;
                    scope.institution.institutionID = ui.item.id;
                    element[0].blur();
                  }
                });
              });

              element.on('blur', function () {
                var instNameCorrect = false;
                var elemValue = element.val();

                if (elemValue !== '') {
                  for (var i = 0; i < institutions.length; i++) {
                    if (institutions[i].acronym + ', ' + institutions[i].name + ', ' + institutions[i].countryCode === elemValue  || institutions[i].name === elemValue) {
                      instNameCorrect = true;
                    }
                  }
                  if (instNameCorrect === false) {
                    scope.institution.institutionName = '';
                  }
                }
                element.autocomplete('destroy');
              });

              element.bind('keydown keypress', function (event) {
                if (event.which === 27) { // 27 = esc key
                  element[0].blur();
                  event.preventDefault();
                  event.stopPropagation();
                }
              });

              scope.$watch(function () {
                return modelCtrl.$modelValue;
              }, function (newValue, oldValue) {
                if (newValue != oldValue) {
                  if (newValue === '') {
                    scope.institution.institutionID = '';
                  }
                }
              }, true);

            }
          }
        }
      };
    }]);
