'use strict';
define([], function() {
  var resizableModal = function($document, $rootScope) {
    return {
      restrict: 'A',

      link: function(scope, element, attrs) {
        // add direction items
        var box = angular.element(element),
          html =
            '<div class="dir" id="nw"></div>' +
            '<div class="dir" id="n"></div>' +
            '<div class="dir" id="ne"></div>' +
            '<div class="dir" id="w"></div>' +
            '<div class="dir" id="e"></div>' +
            '<div class="dir" id="sw"></div>' +
            '<div class="dir" id="s"></div>' +
            '<div class="dir" id="se"></div>';

        box.addClass('resizableModal');
        box.prepend(html);

        var prev_x = -1,
          prev_y = -1,
          dir = null,
          directions = element.find('.dir');

        directions.bind('mousedown', function(e) {
          e.preventDefault();
          prev_x = e.clientX;
          prev_y = e.clientY;
          dir = angular.element(event.target || event.srcElement).prop('id');
        });

        $document.mousemove(function(e) {
          if (prev_x == -1) return;

          var boxX = box.prop('offsetLeft'),
            boxY = box.prop('offsetTop'),
            boxW = box[0].offsetWidth,
            boxH = box[0].offsetHeight,
            dx = e.clientX - prev_x,
            dy = e.clientY - prev_y;

          if (dir.indexOf('n') > -1) {
            boxY += dy;
            boxH -= dy;
          }
          if (dir.indexOf('s') > -1) {
            boxH += dy;
          }
          if (dir.indexOf('w') > -1) {
            boxX += dx;
            boxW -= dx;
          }
          if (dir.indexOf('e') > -1) {
            boxW += dx;
          }

          box[0].style.top = boxY + 'px';
          box[0].style.left = boxX + 'px';
          box[0].style.width = boxW + 'px';
          box[0].style.height = boxH + 'px';

          prev_x = e.clientX;
          prev_y = e.clientY;
        });

        $(document).mouseup(function() {
          prev_x = -1;
          prev_y = -1;
        });
      },
    };
  };

  resizableModal.$inject = ['$document', '$rootScope'];
  return resizableModal;
});
