/**
 * An element which displays a Dockerfile command nicely formatted, with optional link to the
 * image (for FROM commands that link to us or to the DockerHub).
 */
angular.module('quay').directive('dockerfileCommand', function () {
  var directiveDefinitionObject = {
    priority: 0,
    templateUrl: '/static/directives/dockerfile-command.html',
    replace: false,
    transclude: false,
    restrict: 'C',
    scope: {
      'command': '=command'
    },
    controller: function($scope, $element, UtilService, Config) {
      var registryHandlers = {
        'quay.io': function(pieces) {
          var rnamespace =  pieces[pieces.length - 2];
          var rname = pieces[pieces.length - 1].split(':')[0];
          return '/repository/' + rnamespace + '/' + rname + '/';
        },

        '': function(pieces) {
          var rnamespace = pieces.length == 1 ? '_' : 'u/' + pieces[0];
          var rname = pieces[pieces.length - 1].split(':')[0];
          return 'https://registry.hub.docker.com/' + rnamespace + '/' + rname + '/';
        }
      };

      registryHandlers[Config.getDomain()] = registryHandlers['quay.io'];

      var kindHandlers = {
        'FROM': function(title) {
          var pieces = title.split('/');
          var registry = pieces.length < 3 ? '' : pieces[0];
          if (!registryHandlers[registry]) {
            return title;
          }

          return '<i class="fa fa-hdd-o"></i> <a href="' + registryHandlers[registry](pieces) + '" target="_blank">' + title + '</a>';
        }
      };

      $scope.getCommandKind = function(title) {
        var space = title.indexOf(' ');
        return title.substring(0, space);
      };

      $scope.getCommandTitleHtml = function(title) {
        var space = title.indexOf(' ');
        if (space <= 0) {
          return UtilService.textToSafeHtml(title);
        }

        var kind = $scope.getCommandKind(title);
        var sanitized = UtilService.textToSafeHtml(title.substring(space + 1));

        var handler = kindHandlers[kind || ''];
        if (handler) {
          return handler(sanitized);
        } else {
          return sanitized;
        }
      };
    }
  };
  return directiveDefinitionObject;
});