/**
 * An element which displays a dialog with docker auth credentials for an entity.
 */
angular.module('quay').directive('dockerAuthDialog', function (Config) {
  var directiveDefinitionObject = {
    priority: 0,
    templateUrl: '/static/directives/docker-auth-dialog.html',
    replace: false,
    transclude: true,
    restrict: 'C',
    scope: {
      'username': '=username',
      'token': '=token',
      'shown': '=shown',
      'counter': '=counter',
      'supportsRegenerate': '@supportsRegenerate',
      'regenerate': '&regenerate'
    },
    controller: function($scope, $element) {
      var updateCommand = function() {
        var escape = function(v) {
          if (!v) { return v; }
          return v.replace('$', '\\$');
        };
        $scope.command = 'docker login -e="." -u="' + escape($scope.username) +
          '" -p="' + $scope.token + '" ' + Config['SERVER_HOSTNAME'];
      };

      $scope.$watch('username', updateCommand);
      $scope.$watch('token', updateCommand);

      $scope.regenerating = true;

      $scope.askRegenerate = function() {
        bootbox.confirm('Are you sure you want to regenerate the token? All existing login credentials will become invalid', function(resp) {
          if (resp) {
            $scope.regenerating = true;
            $scope.regenerate({'username': $scope.username, 'token': $scope.token});
          }
        });
      };

      $scope.isDownloadSupported = function() {
        var isSafari = /^((?!chrome).)*safari/i.test(navigator.userAgent);
        if (isSafari) {
          // Doesn't work properly in Safari, sadly.
          return false;
        }

        try { return !!new Blob(); } catch(e) {}
        return false;
      };

      $scope.downloadCfg = function() {
        var auth = $.base64.encode($scope.username + ":" + $scope.token);
        config = {}
        config[Config['SERVER_HOSTNAME']] = {
          "auth": auth,
          "email": ""
        };

        var file = JSON.stringify(config, null, ' ');
        var blob = new Blob([file]);
        saveAs(blob, '.dockercfg');
      };

      var show = function(r) {
        $scope.regenerating = false;

        if (!$scope.shown || !$scope.username || !$scope.token) {
          $('#dockerauthmodal').modal('hide');
          return;
        }

        $('#copyClipboard').clipboardCopy();
        $('#dockerauthmodal').modal({});
      };

      $scope.$watch('counter', show);
      $scope.$watch('shown', show);
      $scope.$watch('username', show);
      $scope.$watch('token', show);
    }
  };
  return directiveDefinitionObject;
});
