/**
 * An element which displays charts and graphs representing the current installation of the
 * application. This control requires superuser access and *must be disabled when not visible*.
 */
angular.module('quay').directive('psUsageGraph', function () {
  var directiveDefinitionObject = {
    priority: 0,
    templateUrl: '/static/directives/ps-usage-graph.html',
    replace: false,
    transclude: false,
    restrict: 'C',
    scope: {
      'isEnabled': '=isEnabled'
    },
    controller: function($scope, $element) {
      $scope.counter = -1;
      $scope.data = null;

      var source = null;

      var connect = function() {
        if (source) { return; }
        source = new EventSource('/realtime/ps');
        source.onmessage = function(e) {
          $scope.$apply(function() {
            $scope.counter++;
            $scope.data = JSON.parse(e.data);
          });
        };
      };

      var disconnect = function() {
        if (!source) { return; }
        source.close();
        source = null;
      };

      $scope.$watch('isEnabled', function(value) {
        if (value) {
          connect();
        } else {
          disconnect();
        }
      });

      $scope.$on("$destroy", disconnect);
    }
  };
  return directiveDefinitionObject;
});