/**
 * An element which allows for entry of markdown content and previewing its rendering.
 */
angular.module('quay').directive('markdownInput', function () {
  var counter = 0;

  var directiveDefinitionObject = {
    priority: 0,
    templateUrl: '/static/directives/markdown-input.html',
    replace: false,
    transclude: false,
    restrict: 'C',
    scope: {
      'content': '=content',
      'canWrite': '=canWrite',
      'contentChanged': '=contentChanged',
      'fieldTitle': '=fieldTitle'
    },
    controller: function($scope, $element) {
      var elm = $element[0];

      $scope.id = (counter++);

      $scope.editContent = function() {
        if (!$scope.canWrite) { return; }

        if (!$scope.markdownDescriptionEditor) {
          var converter = Markdown.getSanitizingConverter();
          var editor = new Markdown.Editor(converter, '-description-' + $scope.id);
          editor.run();
          $scope.markdownDescriptionEditor = editor;
        }

        $('#wmd-input-description-' + $scope.id)[0].value = $scope.content;
        $(elm).find('.modal').modal({});
      };

      $scope.saveContent = function() {
        $scope.content = $('#wmd-input-description-' + $scope.id)[0].value;
        $(elm).find('.modal').modal('hide');

        if ($scope.contentChanged) {
          $scope.contentChanged($scope.content);
        }
      };
    }
  };
  return directiveDefinitionObject;
});
