'use strict';

var Collections = require('../../../util/Collections');

var saveClear = require('../../../util/Removal').saveClear;


/**
 * A handler that implements reversible deletion of shapes.
 *
 */
function DeleteShapeHandler(canvas, modeling) {
  this._canvas = canvas;
  this._modeling = modeling;
}

DeleteShapeHandler.$inject = [ 'canvas', 'modeling' ];

module.exports = DeleteShapeHandler;


/**
 * - Remove connections
 * - Remove all direct children
 */
DeleteShapeHandler.prototype.preExecute = function(context) {

  var modeling = this._modeling;

  var shape = context.shape,
      label = shape.label;

  // Clean up on removeShape(label)
  if (shape.labelTarget) {
    context.labelTarget = shape.labelTarget;
    shape.labelTarget = null;
  }

  // Remove label
  if (label) {
    this._modeling.removeShape(label);
  }

  // remove connections
  saveClear(shape.incoming, function(connection) {
    // To make sure that the connection isn't removed twice
    // For example if a container is removed
    modeling.removeConnection(connection);
  });

  saveClear(shape.outgoing, function(connection) {
    modeling.removeConnection(connection);
  });


  // remove children
  saveClear(shape.children, function(e) {
    modeling.removeShape(e);
  });
};

/**
 * Remove shape and remember the parent
 */
DeleteShapeHandler.prototype.execute = function(context) {
  var canvas = this._canvas;

  var shape = context.shape,
      parent = shape.parent;

  context.parent = parent;
  context.parentIndex = Collections.indexOf(parent.children, shape);

  shape.label = null;

  canvas.removeShape(shape);
};


/**
 * Command revert implementation
 */
DeleteShapeHandler.prototype.revert = function(context) {

  var canvas = this._canvas;

  var shape = context.shape,
      parent = context.parent,
      parentIndex = context.parentIndex,
      labelTarget = context.labelTarget;

  // restore previous location in old parent
  Collections.add(parent.children, shape, parentIndex);

  if (labelTarget) {
    labelTarget.label = shape;
  }

  canvas.addShape(shape, parent);
};

@@ -1434,33 +1434,36 @@
 xt.shape,%0A      
-p
+oldP
 arent = shape.pa
@@ -1479,25 +1479,28 @@
 context.
-p
+oldP
 arent = 
 parent;%0A
@@ -1491,17 +1491,20 @@
 arent = 
-p
+oldP
 arent;%0A 
@@ -1504,33 +1504,36 @@
 rent;%0A  context.
-p
+oldP
 arentIndex = Col
@@ -1549,17 +1549,20 @@
 indexOf(
-p
+oldP
 arent.ch
@@ -1796,25 +1796,28 @@
 hape,%0A      
-p
+oldP
 arent = cont
@@ -1816,25 +1816,28 @@
 t = context.
-p
+oldP
 arent,%0A     
@@ -1837,17 +1837,20 @@
 ,%0A      
-p
+oldP
 arentInd
@@ -1862,17 +1862,20 @@
 context.
-p
+oldP
 arentInd
@@ -1958,17 +1958,20 @@
  in old 
-p
+oldP
 arent%0A  
@@ -1986,17 +1986,20 @@
 ons.add(
-p
+oldP
 arent.ch
@@ -2009,25 +2009,28 @@
 ren, shape, 
-p
+oldP
 arentIndex);
@@ -2113,17 +2113,20 @@
 (shape, 
-p
+oldP
 arent);%0A

align delete context with move