/**
 * An element which displays a small flag representing the given location, as well as a ping
 * latency gauge for that location.
 */
angular.module('quay').directive('locationView', function () {
  var directiveDefinitionObject = {
    priority: 0,
    templateUrl: '/static/directives/location-view.html',
    replace: false,
    transclude: true,
    restrict: 'C',
    scope: {
      'location': '=location'
    },
    controller: function($rootScope, $scope, $element, $http, PingService) {
      var LOCATIONS = {
        'local_us': { 'country': 'US', 'data': 'quay-registry.s3.amazonaws.com', 'title': 'United States' },
        'local_eu': { 'country': 'EU', 'data': 'quay-registry-eu.s3-eu-west-1.amazonaws.com', 'title': 'Europe' },

        's3_us_east_1': { 'country': 'US', 'data': 'quay-registry.s3.amazonaws.com', 'title': 'United States (East)' },
        's3_us_west_1': { 'country': 'US', 'data': 'quay-registry-cali.s3.amazonaws.com', 'title': 'United States (West)' },

        's3_eu_west_1': { 'country': 'EU', 'data': 'quay-registry-eu.s3-eu-west-1.amazonaws.com', 'title': 'Europe' },

        's3_ap_southeast_1': { 'country': 'SG', 'data': 'quay-registry-singapore.s3-ap-southeast-1.amazonaws.com', 'title': 'Singapore' },
        's3_ap_southeast_2': { 'country': 'AU', 'data': 'quay-registry-sydney.s3-ap-southeast-2.amazonaws.com', 'title': 'Australia' },

    //  's3_ap_northeast-1': { 'country': 'JP', 'data': 's3-ap-northeast-1.amazonaws.com', 'title': 'Japan' },
    //  's3_sa_east1': { 'country': 'BR', 'data': 's3-east-1.amazonaws.com', 'title': 'Sao Paulo' }
      };

      $scope.locationPing = null;

      $scope.getLocationTooltip = function(location, ping) {
        var tip = $scope.getLocationTitle(location) + '<br>';
        if (ping == null) {
          tip += '(Loading)';
        } else if (ping < 0) {
          tip += '<br><b>Note: Could not contact server</b>';
        } else {
          tip += 'Estimated Ping: ' + (ping ? ping + 'ms' : '(Loading)');
        }
        return tip;
      };

      $scope.getLocationTitle = function(location) {
        if (!LOCATIONS[location]) {
          return '(Unknown)';
        }
        return 'Image data is located in ' + LOCATIONS[location]['title'];
      };

      $scope.getLocationImage = function(location) {
        if (!LOCATIONS[location]) {
          return 'unknown.png';
        }
        return LOCATIONS[location]['country'] + '.png';
      };

      $scope.getLocationPing = function(location) {
        var url = 'https://' + LOCATIONS[location]['data'] + '/okay.txt';
        PingService.pingUrl($scope, url, function(ping, success, count) {
          if (count == 3 || !success) {
            $scope.locationPing = success ? ping : -1;
          }
        });
      };

      $scope.$watch('location', function(location) {
        if (!location) { return; }
        $scope.getLocationPing(location);
      });
    }
  };
  return directiveDefinitionObject;
});
