$.fn.clipboardCopy = function() {
  if (__zeroClipboardSupported) {
    (new ZeroClipboard($(this)));
    return true;
  }

  this.hide();
  return false;
};

// Initialize the clipboard system.
(function () {
  __zeroClipboardSupported = true;

  ZeroClipboard.config({
    'swfPath': 'static/lib/ZeroClipboard.swf'
  });

  ZeroClipboard.on("error", function(e) {
    __zeroClipboardSupported = false;
  });

  ZeroClipboard.on('aftercopy', function(e) {
    var container = e.target.parentNode.parentNode.parentNode;
    var message = $(container).find('.clipboard-copied-message')[0];
    if (!message) {
      return;
    }

    // Resets the animation.
    var elem = message;
    elem.style.display = 'none';
    elem.classList.remove('animated');

    // Show the notification.
    setTimeout(function() {
      elem.style.display = 'inline-block';
      elem.classList.add('animated');
    }, 10);

    // Reset the notification.
    setTimeout(function() {
      elem.style.display = 'none';
    }, 5000);
  });
})();

/**
 * An element which displays a textfield with a "Copy to Clipboard" icon next to it. Note
 * that this method depends on the clipboard copying library in the lib/ folder.
 */
angular.module('quay').directive('copyBox', function () {
  var directiveDefinitionObject = {
    priority: 0,
    templateUrl: '/static/directives/copy-box.html',
    replace: false,
    transclude: false,
    restrict: 'C',
    scope: {
      'value': '=value',
      'hoveringMessage': '=hoveringMessage',
    },
    controller: function($scope, $element, $rootScope) {
      $scope.disabled = false;

      var number = $rootScope.__copyBoxIdCounter || 0;
      $rootScope.__copyBoxIdCounter = number + 1;
      $scope.inputId = "copy-box-input-" + number;

      var button = $($element).find('.copy-icon');
      var input = $($element).find('input');

      input.attr('id', $scope.inputId);
      button.attr('data-clipboard-target', $scope.inputId);
      $scope.disabled = !button.clipboardCopy();
    }
  };
  return directiveDefinitionObject;
});