/**
 * An element which displays a dialog for requesting or creating a service key.
 */
angular.module('quay').directive('requestServiceKeyDialog', function () {
  var directiveDefinitionObject = {
    priority: 0,
    templateUrl: '/static/directives/request-service-key-dialog.html',
    replace: false,
    transclude: true,
    restrict: 'C',
    scope: {
      'requestKeyInfo': '=requestKeyInfo',
      'keyCreated': '&keyCreated'
    },
    controller: function($scope, $element, $timeout, ApiService) {
      var handleNewKey = function(key) {
        var data = {
          'notes': 'Approved during setup of service ' + key.service
        };

        var params = {
          'kid': key.kid
        };

        ApiService.approveServiceKey(data, params).then(function(resp) {
          $scope.keyCreated({'key': key});
          $scope.step = 2;
        }, ApiService.errorDisplay('Could not approve service key'));
      };

      var checkKeys = function() {
        var isShown = ($element.find('.modal').data('bs.modal') || {}).isShown;
        if (!isShown) {
          return;
        }

        // TODO: filter by service.
        ApiService.listServiceKeys().then(function(resp) {
          var keys = resp['keys'];
          for (var i = 0; i < keys.length; ++i) {
            var key = keys[i];
            if (key.service == $scope.requestKeyInfo.service && !key.approval && key.rotation_duration) {
              handleNewKey(key);
              return;
            }
          }

          $timeout(checkKeys, 1000);
        }, ApiService.errorDisplay('Could not list service keys'));
      };

      $scope.show = function() {
        $scope.working = false;
        $scope.step = 0;
        $scope.requestKind = null;
        $scope.preshared = {
          'name': $scope.requestKeyInfo.service + ' Service Key',
          'notes': 'Created during setup for service `' + $scope.requestKeyInfo.service + '`'
        };

        $element.find('.modal').modal({});
      };

      $scope.hide = function() {
        $scope.loading = false;
        $element.find('.modal').modal('hide');
      };

      $scope.showGenerate = function() {
        $scope.step = 1;
      };

      $scope.startApproval = function() {
        $scope.step = 1;
        checkKeys();
      };

      $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.downloadPrivateKey = function(key) {
        var blob = new Blob([key.private_key]);
        saveAs(blob, key.service + '.pem');
      };

      $scope.createPresharedKey = function() {
        $scope.working = true;

        var data = {
          'name': $scope.preshared.name,
          'service': $scope.requestKeyInfo.service,
          'expiration': $scope.preshared.expiration || null,
          'notes': $scope.preshared.notes
        };

        ApiService.createServiceKey(data).then(function(resp) {
          $scope.working = false;
          $scope.step = 2;
          $scope.createdKey = resp;
          $scope.keyCreated({'key': resp});
        }, ApiService.errorDisplay('Could not create service key'));
      };

      $scope.$watch('requestKeyInfo', function(info) {
        if (info && info.service) {
          $scope.show();
        }
      });
    }
  };
  return directiveDefinitionObject;
});