(function() {
  /**
   * Page to view the details of a single image.
   */
  angular.module('quayPages').config(['pages', function(pages) {
    pages.create('image-view', 'image-view.html', ImageViewCtrl, {
      'newLayout': true,
      'title': '{{ image.id }}',
      'description': 'Image {{ image.id }}'
    }, ['layout'])

    pages.create('image-view', 'old-image-view.html', OldImageViewCtrl, {
    }, ['old-layout']);
  }]);

  function ImageViewCtrl($scope, $routeParams, $rootScope, $timeout, ApiService, ImageMetadataService) {
    var namespace = $routeParams.namespace;
    var name = $routeParams.name;
    var imageid = $routeParams.image;

    var loadImage = function() {
      var params = {
        'repository': namespace + '/' + name,
        'image_id': imageid
      };

      $scope.imageResource = ApiService.getImageAsResource(params).get(function(image) {
        $scope.image = image;
        $scope.reversedHistory = image.history.reverse();
      });
    };

    var loadRepository = function() {
      var params = {
        'repository': namespace + '/' + name
      };

      $scope.repositoryResource = ApiService.getRepoAsResource(params).get(function(repo) {
        $scope.repository = repo;
      });
    };

    loadImage();
    loadRepository();

    $scope.downloadChanges = function() {
      if ($scope.changesResource) { return; }

      var params = {
        'repository': namespace + '/' + name,
        'image_id': imageid
      };

      $scope.changesResource = ApiService.getImageChangesAsResource(params).get(function(changes) {
        var combinedChanges = [];
        var addCombinedChanges = function(c, kind) {
          for (var i = 0;  i < c.length; ++i) {
            combinedChanges.push({
              'kind': kind,
              'file': c[i]
            });
          }
        };

        addCombinedChanges(changes.added, 'added');
        addCombinedChanges(changes.removed, 'removed');
        addCombinedChanges(changes.changed, 'changed');

        $scope.combinedChanges = combinedChanges;
        $scope.imageChanges = changes;
        $scope.initializeTree();
      });
    };

    $scope.initializeTree = function() {
      if ($scope.tree || !$scope.combinedChanges.length) { return; }

      $scope.tree = new ImageFileChangeTree($scope.image, $scope.combinedChanges);
      $timeout(function() {
        $scope.tree.draw('changes-tree-container');
      }, 100);
    };
  }

  function OldImageViewCtrl($scope, $routeParams, $rootScope, $timeout, ApiService, ImageMetadataService) {
    var namespace = $routeParams.namespace;
    var name = $routeParams.name;
    var imageid = $routeParams.image;

    $scope.getFormattedCommand = ImageMetadataService.getFormattedCommand;

    $scope.parseDate = function(dateString) {
      return Date.parse(dateString);
    };

    $scope.getFolder = function(filepath) {
      var index = filepath.lastIndexOf('/');
      if (index < 0) {
        return '';
      }
      return filepath.substr(0, index + 1);
    };

    $scope.getFolders = function(filepath) {
      var index = filepath.lastIndexOf('/');
      if (index < 0) {
        return '';
      }

      return filepath.substr(0, index).split('/');
    };

    $scope.getFilename = function(filepath) {
      var index = filepath.lastIndexOf('/');
      if (index < 0) {
        return filepath;
      }
      return filepath.substr(index + 1);
    };

    $scope.setFolderFilter = function(folderPath, index) {
      var parts = folderPath.split('/');
      parts = parts.slice(0, index + 1);
      $scope.setFilter(parts.join('/'));
    };

    $scope.setFilter = function(filter) {
      $scope.search = {};
      $scope.search['$'] = filter;
      document.getElementById('change-filter').value = filter;
    };

    $scope.initializeTree = function() {
      if ($scope.tree) { return; }

      $scope.tree = new ImageFileChangeTree($scope.image, $scope.combinedChanges);
      $timeout(function() {
        $scope.tree.draw('changes-tree-container');
      }, 10);
    };

    var fetchRepository = function() {
      var params = {
        'repository': namespace + '/' + name
      };

      ApiService.getRepoAsResource(params).get(function(repo) {
        $scope.repo = repo;
      });
    };

    var fetchImage = function() {
      var params = {
        'repository': namespace + '/' + name,
        'image_id': imageid
      };

      $scope.image = ApiService.getImageAsResource(params).get(function(image) {
        if (!$scope.repo) {
          $scope.repo = {
            'name': name,
            'namespace': namespace,
            'is_public': true
          };
        }

        $rootScope.title = 'View Image - ' + image.id;
        $rootScope.description = 'Viewing docker image ' + image.id + ' under repository ' + namespace + '/' + name +
          ': Image changes tree and list view';

        // Fetch the image's changes.
        fetchChanges();
        return image;
      });
    };

    var fetchChanges = function() {
      var params = {
        'repository': namespace + '/' + name,
        'image_id': imageid
      };

      ApiService.getImageChanges(null, params).then(function(changes) {
        var combinedChanges = [];
        var addCombinedChanges = function(c, kind) {
          for (var i = 0;  i < c.length; ++i) {
            combinedChanges.push({
              'kind': kind,
              'file': c[i]
            });
          }
        };

        addCombinedChanges(changes.added, 'added');
        addCombinedChanges(changes.removed, 'removed');
        addCombinedChanges(changes.changed, 'changed');

        $scope.combinedChanges = combinedChanges;
        $scope.imageChanges = changes;
      });
    };

    // Fetch the repository.
    fetchRepository();

    // Fetch the image.
    fetchImage();
  }
})();