/**
 * An element which displays a repository search box.
 */
angular.module('quay').directive('repoSearch', function () {
  var number = 0;
  var directiveDefinitionObject = {
    priority: 0,
    templateUrl: '/static/directives/repo-search.html',
    replace: false,
    transclude: false,
    restrict: 'C',
    scope: {
    },
    controller: function($scope, $element, $location, UserService, Restangular, UtilService) {
      var searchToken = 0;
      $scope.$watch( function () { return UserService.currentUser(); }, function (currentUser) {
        ++searchToken;
      }, true);

      var repoHound = new Bloodhound({
        name: 'repositories',
        remote: {
          url: '/api/v1/find/repository?query=%QUERY',
          replace: function (url, uriEncodedQuery) {
            url = url.replace('%QUERY', uriEncodedQuery);
            url += '&cb=' + searchToken;
            return url;
          },
          filter: function(data) {
            var datums = [];
            for (var i = 0; i < data.repositories.length; ++i) {
              var repo = data.repositories[i];
              datums.push({
                'value': repo.name,
                'tokens': [repo.name, repo.namespace],
                'repo': repo
              });
            }
            return datums;
          }
        },
        datumTokenizer: function(d) {
          return Bloodhound.tokenizers.whitespace(d.val);
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace
      });
      repoHound.initialize();

      var element = $($element[0].childNodes[0]);
      element.typeahead({ 'highlight': true }, {
        source: repoHound.ttAdapter(),
        templates: {
          'suggestion': function (datum) {
            template = '<div class="repo-mini-listing">';
            template += '<i class="fa fa-hdd-o fa-lg"></i>'
            template += '<span class="name">' + datum.repo.namespace +'/' + datum.repo.name + '</span>'
            if (datum.repo.description) {
              template += '<span class="description">' + UtilService.getFirstMarkdownLineAsText(datum.repo.description) + '</span>'
            }

            template += '</div>'
            return template;
          }
        }
      });

      element.on('typeahead:selected', function (e, datum) {
        element.typeahead('val', '');
        $scope.$apply(function() {
          $location.path('/repository/' + datum.repo.namespace + '/' + datum.repo.name);
        });
      });
    }
  };
  return directiveDefinitionObject;
});
