/**
 * An element which displays the vulnerabilities in an image.
 */
angular.module('quay').directive('imageVulnerabilityView', function () {
  var directiveDefinitionObject = {
    priority: 0,
    templateUrl: '/static/directives/image-vulnerability-view.html',
    replace: false,
    transclude: true,
    restrict: 'C',
    scope: {
      'repository': '=repository',
      'image': '=image',
      'isEnabled': '=isEnabled'
    },
    controller: function($scope, $element, Config, ApiService, VulnerabilityService, AngularViewArray, ImageMetadataService) {
      var imageMap = null;

      $scope.securityVulnerabilities = [];

      $scope.options = {
        'vulnFilter': null,
        'fixableVulns': false,
        'predicate': 'score',
        'reverse': false,
      };

      $scope.tablePredicateClass = function(name, predicate, reverse) {
        if (name != predicate) {
          return '';
        }

        return 'current ' + (reverse ? 'reversed' : '');
      };

      $scope.orderBy = function(predicate) {
        if (predicate == $scope.options.predicate) {
          $scope.options.reverse = !$scope.options.reverse;
          return;
        }

        $scope.options.reverse = false;
        $scope.options.predicate = predicate;
      };

      $scope.getCVSSColor = function(score) {
        return VulnerabilityService.getCVSSColor(score);
      };

      $scope.toggleDetails = function(vuln) {
        vuln.expanded = !vuln.expanded;
      };

      var buildOrderedVulnerabilities = function() {
        var vulnerabilities = $scope.securityVulnerabilities.slice(0);

        $scope.orderedVulnerabilities = AngularViewArray.create();
        vulnerabilities.forEach(function(v) {
          var vulnFilter = $scope.options.vulnFilter;
          if (vulnFilter) {
            if ((v['name'].indexOf(vulnFilter) < 0) &&
                (v['featureName'].indexOf(vulnFilter) < 0) &&
                (v['imageCommand'].indexOf(vulnFilter) < 0)) {
              return;
            }
          }

          if ($scope.options.fixableVulns && !v['fixedInVersion']) {
            return;
          }

          $scope.orderedVulnerabilities.push(v);
        });

        $scope.orderedVulnerabilities.entries.sort(function(a, b) {
          var left = a[$scope.options['predicate']];
          var right = b[$scope.options['predicate']];

          if ($scope.options['predicate'] == 'score') {
            left = left * 1;
            right = right * 1;
          }

          if (left == null) {
            left = '0.00';
          }

          if (right == null) {
            right = '0.00';
          }

          if (left == right) {
            return 0;
          }

          return left > right ? -1 : 1;
        });

        if ($scope.options['reverse']) {
          $scope.orderedVulnerabilities.entries.reverse();
        }

        $scope.orderedVulnerabilities.setVisible(true);
      };

      var buildChart = function() {
        var chartData = $scope.priorityBreakdown;
        if ($scope.priorityBreakdown.length == 0) {
          chartData = [{
            'label': 'None',
            'value': 1,
            'color': '#2FC98E'
          }];
        }

        var colors = [];
        for (var i = 0; i < chartData.length; ++i) {
          colors.push(chartData[i].color);
        }

        nv.addGraph(function() {
          var chart = nv.models.pieChart()
              .x(function(d) { return d.label })
              .y(function(d) { return d.value })
              .margin({left: -10, right: -10, top: -10, bottom: -10})
              .showLegend(false)
              .showLabels(true)
              .labelThreshold(.05)
              .labelType("percent")
              .donut(true)
              .color(colors)
              .donutRatio(0.5);

            d3.select("#vulnDonutChart svg")
                .datum(chartData)
                .transition()
                .duration(350)
                .call(chart);

          return chart;
        });
      };

      var buildFeaturesAndVulns = function(data) {
        $scope.securityFeatures = [];
        $scope.securityVulnerabilities = [];
        $scope.priorityBreakdown = [];

        var severityMap = {};

        if (data && data.Layer && data.Layer.Features) {
          data.Layer.Features.forEach(function(feature) {
            feature_obj = {
              'name': feature.Name,
              'namespace': feature.Namespace,
              'version': feature.Version,
              'addedBy': feature.AddedBy
            }

            feature_vulnerabilities = [];

            if (feature.Vulnerabilities) {
              feature.Vulnerabilities.forEach(function(vuln) {
                var severity = VulnerabilityService.LEVELS[vuln['Severity']];
                var score = severity.score;
                if (vuln.Metadata && vuln.Metadata.NVD && vuln.Metadata.NVD.CVSSv2 && vuln.Metadata.NVD.CVSSv2.Score) {
                  score = vuln.Metadata.NVD.CVSSv2.Score;
                  severity = VulnerabilityService.getSeverityForCVSS(score);
                }

                var imageId = feature.AddedBy.split('.')[0];

                vuln_obj = {
                  'name': vuln.Name,
                  'namespace': vuln.Namespace,
                  'description': vuln.Description,
                  'link': vuln.Link,
                  'severity': vuln.Severity,
                  'metadata': vuln.Metadata,
                  'feature': jQuery.extend({}, feature_obj),

                  'featureName': feature.Name,
                  'fixedInVersion': vuln.FixedBy,
                  'introducedInVersion': feature.Version,
                  'imageId': imageId,
                  'imageCommand': ImageMetadataService.getImageCommand($scope.image, imageId),
                  'score': score,

                  'expanded': false,
                }

                feature_vulnerabilities.push(vuln_obj)
                $scope.securityVulnerabilities.push(vuln_obj);

                if (severityMap[severity['index']] == undefined) {
                  severityMap[severity['index']] = 0;
                }

                severityMap[severity['index']]++;
              });
            }

            feature_obj['vulnerabilities'] = feature_vulnerabilities;
            $scope.securityFeatures.push(feature_obj);
          });

          var levels = VulnerabilityService.getLevels();
          for (var i = 0; i < levels.length; ++i) {
            if (severityMap[levels[i]['index']]) {
              $scope.priorityBreakdown.push({
                'label': levels[i].title,
                'value': severityMap[levels[i]['index']],
                'color': levels[i].color
              })
            }
          }
        }

        buildOrderedVulnerabilities();
      };

      var loadImageVulnerabilities = function() {
        if ($scope.securityResource) {
          return;
        }

        var params = {
          'repository': $scope.repository.namespace + '/' + $scope.repository.name,
          'imageid': $scope.image.id,
          'vulnerabilities': true,
        };

        $scope.securityResource = ApiService.getRepoImageSecurityAsResource(params).get(function(resp) {
          $scope.securityStatus = resp.status;
          buildFeaturesAndVulns(resp.data);
          buildChart();
          return resp;
        });
      };

      $scope.$watch('options.predicate', buildOrderedVulnerabilities);
      $scope.$watch('options.reverse', buildOrderedVulnerabilities);
      $scope.$watch('options.vulnFilter', buildOrderedVulnerabilities);
      $scope.$watch('options.fixableVulns', buildOrderedVulnerabilities);

      $scope.$watch('isEnabled', function(isEnabled) {
        if ($scope.isEnabled && $scope.repository && $scope.image) {
          loadImageVulnerabilities();
        }
      });
    }
  };
  return directiveDefinitionObject;
});