/**
 * An element which displays a build error in a nice format.
 */
angular.module('quay').directive('buildLogError', function () {
  var directiveDefinitionObject = {
    priority: 0,
    templateUrl: '/static/directives/build-log-error.html',
    replace: false,
    transclude: false,
    restrict: 'C',
    scope: {
      'error': '=error',
      'entries': '=entries'
    },
    controller: function($scope, $element, Config) {
      $scope.isInternalError = function() {
        var entry = $scope.entries[$scope.entries.length - 1];
        return entry && entry.data && entry.data['internal_error'];
      };

      $scope.getLocalPullInfo = function() {
        if ($scope.entries.__localpull !== undefined) {
          return $scope.entries.__localpull;
        }

        var localInfo = {
          'isLocal': false
        };

        // Find the 'pulling' phase entry, and then extra any metadata found under
        // it.
        for (var i = 0; i < $scope.entries.length; ++i) {
          var entry = $scope.entries[i];
          if (entry.type == 'phase' && entry.message == 'pulling') {
            for (var j = 0; j < entry.logs.length(); ++j) {
              var log = entry.logs.get(j);
              if (log.data && log.data.phasestep == 'login') {
                localInfo['login'] = log.data;
              }

              if (log.data && log.data.phasestep == 'pull') {
                var repo_url = log.data['repo_url'];
                var repo_and_tag = repo_url.substring(Config.SERVER_HOSTNAME.length + 1);
                var tagIndex = repo_and_tag.lastIndexOf(':');
                var repo = repo_and_tag.substring(0, tagIndex);

                localInfo['repo_url'] = repo_url;
                localInfo['repo'] = repo;

                localInfo['isLocal'] = repo_url.indexOf(Config.SERVER_HOSTNAME + '/') == 0;
              }
            }
            break;
          }
        }

        return $scope.entries.__localpull = localInfo;
      };
    }
  };
  return directiveDefinitionObject;
});