import { isArray, forEach } from "../../../../min-dash/dist/index.esm.mjs";
function Selection(eventBus, canvas) {
  this._eventBus = eventBus;
  this._canvas = canvas;
  this._selectedElements = [];
  var self = this;
  eventBus.on(["shape.remove", "connection.remove"], function(e) {
    var element = e.element;
    self.deselect(element);
  });
  eventBus.on(["diagram.clear", "root.set"], function(e) {
    self.select(null);
  });
}
Selection.$inject = ["eventBus", "canvas"];
Selection.prototype.deselect = function(element) {
  var selectedElements = this._selectedElements;
  var idx = selectedElements.indexOf(element);
  if (idx !== -1) {
    var oldSelection = selectedElements.slice();
    selectedElements.splice(idx, 1);
    this._eventBus.fire("selection.changed", { oldSelection, newSelection: selectedElements });
  }
};
Selection.prototype.get = function() {
  return this._selectedElements;
};
Selection.prototype.isSelected = function(element) {
  return this._selectedElements.indexOf(element) !== -1;
};
Selection.prototype.select = function(elements, add) {
  var selectedElements = this._selectedElements, oldSelection = selectedElements.slice();
  if (!isArray(elements)) {
    elements = elements ? [elements] : [];
  }
  var canvas = this._canvas;
  var rootElement = canvas.getRootElement();
  elements = elements.filter(function(element) {
    var elementRoot = canvas.findRoot(element);
    return rootElement === elementRoot;
  });
  if (add) {
    forEach(elements, function(element) {
      if (selectedElements.indexOf(element) !== -1) {
        return;
      } else {
        selectedElements.push(element);
      }
    });
  } else {
    this._selectedElements = selectedElements = elements.slice();
  }
  this._eventBus.fire("selection.changed", { oldSelection, newSelection: selectedElements });
};
export {
  Selection as default
};
