function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import "core-js/modules/es.array.iterator.js";
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.string.iterator.js";
import "core-js/modules/es.weak-map.js";
import "core-js/modules/web.dom-collections.iterator.js";
import "core-js/modules/es.weak-set.js";
import "core-js/modules/es.map.js";
import "core-js/modules/es.set.js";
import "core-js/modules/es.array.from.js";
import "core-js/modules/web.dom-collections.for-each.js";
import "core-js/modules/es.array.flat.js";
import "core-js/modules/es.array.unscopables.flat.js";
import "core-js/modules/es.array.map.js";
import "core-js/modules/es.array.concat.js";
import "core-js/modules/es.symbol.to-primitive.js";
import "core-js/modules/es.date.to-primitive.js";
import "core-js/modules/es.symbol.js";
import "core-js/modules/es.symbol.description.js";
import "core-js/modules/es.number.constructor.js";
import "core-js/modules/es.symbol.iterator.js";
import "core-js/modules/es.array.slice.js";
import "core-js/modules/es.regexp.to-string.js";
import "core-js/modules/es.function.name.js";
import "core-js/modules/es.regexp.exec.js";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _classPrivateMethodInitSpec(obj, privateSet) { _checkPrivateRedeclaration(obj, privateSet); privateSet.add(obj); }
function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; }
function _classPrivateFieldGet(receiver, privateMap) { var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "get"); return _classApplyDescriptorGet(receiver, descriptor); }
function _classApplyDescriptorGet(receiver, descriptor) { if (descriptor.get) { return descriptor.get.call(receiver); } return descriptor.value; }
function _classPrivateFieldSet(receiver, privateMap, value) { var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "set"); _classApplyDescriptorSet(receiver, descriptor, value); return value; }
function _classExtractFieldDescriptor(receiver, privateMap, action) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to " + action + " private field on non-instance"); } return privateMap.get(receiver); }
function _classApplyDescriptorSet(receiver, descriptor, value) { if (descriptor.set) { descriptor.set.call(receiver, value); } else { if (!descriptor.writable) { throw new TypeError("attempted to set read only private field"); } descriptor.value = value; } }
import { removeClass, addClass } from "../../../../helpers/dom/element.mjs";
import { SelectionScanner } from "./scanner.mjs";
import Border from "./border/border.mjs";
/**
 * Module responsible for rendering selections (CSS classes) and borders based on the
 * collection of the Selection instances provided throughout the `selections` Walkontable
 * setting.
 *
 * @private
 */
var _activeOverlaysWot = /*#__PURE__*/new WeakMap();
var _selections = /*#__PURE__*/new WeakMap();
var _scanner = /*#__PURE__*/new WeakMap();
var _appliedClasses = /*#__PURE__*/new WeakMap();
var _destroyListeners = /*#__PURE__*/new WeakMap();
var _selectionBorders = /*#__PURE__*/new WeakMap();
var _resetCells = /*#__PURE__*/new WeakSet();
export var SelectionManager = /*#__PURE__*/function () {
  function SelectionManager(selections) {
    _classCallCheck(this, SelectionManager);
    /**
     * Resets the elements to their initial state (remove the CSS classes that are added in the
     * previous render cycle).
     */
    _classPrivateMethodInitSpec(this, _resetCells);
    /**
     * The overlay's Walkontable instance that are currently processed.
     *
     * @type {Walkontable}
     */
    _classPrivateFieldInitSpec(this, _activeOverlaysWot, {
      writable: true,
      value: void 0
    });
    /**
     * The Highlight instance that holds Selections instances within it.
     *
     * @type {Highlight|null}
     */
    _classPrivateFieldInitSpec(this, _selections, {
      writable: true,
      value: void 0
    });
    /**
     * The SelectionScanner allows to scan and collect the cell and header elements that matches
     * to the coords defined in the selections.
     *
     * @type {SelectionScanner}
     */
    _classPrivateFieldInitSpec(this, _scanner, {
      writable: true,
      value: new SelectionScanner()
    });
    /**
     * The Map tracks applied CSS classes. It's used to reset the elements state to their initial state.
     *
     * @type {WeakMap}
     */
    _classPrivateFieldInitSpec(this, _appliedClasses, {
      writable: true,
      value: new WeakMap()
    });
    /**
     * The Map tracks applied "destroy" listeners for Selection instances.
     *
     * @type {WeakMap}
     */
    _classPrivateFieldInitSpec(this, _destroyListeners, {
      writable: true,
      value: new WeakSet()
    });
    /**
     * The Map holds references to Border classes for Selection instances which requires that when
     * the "border" setting is defined.
     *
     * @type {Map}
     */
    _classPrivateFieldInitSpec(this, _selectionBorders, {
      writable: true,
      value: new Map()
    });
    _classPrivateFieldSet(this, _selections, selections);
  }

  /**
   * Sets the active Walkontable instance.
   *
   * @param {Walkontable} activeWot The overlays or master Walkontable instance.
   * @returns {SelectionManager}
   */
  _createClass(SelectionManager, [{
    key: "setActiveOverlay",
    value: function setActiveOverlay(activeWot) {
      _classPrivateFieldSet(this, _activeOverlaysWot, activeWot);
      _classPrivateFieldGet(this, _scanner).setActiveOverlay(_classPrivateFieldGet(this, _activeOverlaysWot));
      if (!_classPrivateFieldGet(this, _appliedClasses).has(_classPrivateFieldGet(this, _activeOverlaysWot))) {
        _classPrivateFieldGet(this, _appliedClasses).set(_classPrivateFieldGet(this, _activeOverlaysWot), new Set());
      }
      return this;
    }

    /**
     * Gets the Selection instance of the "focus" type.
     *
     * @returns {Selection|null}
     */
  }, {
    key: "getFocusSelection",
    value: function getFocusSelection() {
      return _classPrivateFieldGet(this, _selections) !== null ? _classPrivateFieldGet(this, _selections).getFocus() : null;
    }

    /**
     * Gets the Selection instance of the "area" type.
     *
     * @returns {Selection|null}
     */
  }, {
    key: "getAreaSelection",
    value: function getAreaSelection() {
      return _classPrivateFieldGet(this, _selections) !== null ? _classPrivateFieldGet(this, _selections).createLayeredArea() : null;
    }

    /**
     * Gets the Border instance associated with Selection instance.
     *
     * @param {Selection} selection The selection instance.
     * @returns {Border|null} Returns the Border instance (new for each overlay Walkontable instance).
     */
  }, {
    key: "getBorderInstance",
    value: function getBorderInstance(selection) {
      if (!selection.settings.border) {
        return null;
      }
      if (_classPrivateFieldGet(this, _selectionBorders).has(selection)) {
        var borders = _classPrivateFieldGet(this, _selectionBorders).get(selection);
        if (borders.has(_classPrivateFieldGet(this, _activeOverlaysWot))) {
          return borders.get(_classPrivateFieldGet(this, _activeOverlaysWot));
        }
        var _border = new Border(_classPrivateFieldGet(this, _activeOverlaysWot), selection.settings);
        borders.set(_classPrivateFieldGet(this, _activeOverlaysWot), _border);
        return _border;
      }
      var border = new Border(_classPrivateFieldGet(this, _activeOverlaysWot), selection.settings);
      _classPrivateFieldGet(this, _selectionBorders).set(selection, new Map([[_classPrivateFieldGet(this, _activeOverlaysWot), border]]));
      return border;
    }

    /**
     * Gets all Border instances associated with Selection instance for all overlays.
     *
     * @param {Selection} selection The selection instance.
     * @returns {Border[]}
     */
  }, {
    key: "getBorderInstances",
    value: function getBorderInstances(selection) {
      var _classPrivateFieldGet2, _classPrivateFieldGet3;
      return Array.from((_classPrivateFieldGet2 = (_classPrivateFieldGet3 = _classPrivateFieldGet(this, _selectionBorders).get(selection)) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.values()) !== null && _classPrivateFieldGet2 !== void 0 ? _classPrivateFieldGet2 : []);
    }

    /**
     * Destroys the Border instance associated with Selection instance.
     *
     * @param {Selection} selection The selection instance.
     */
  }, {
    key: "destroyBorders",
    value: function destroyBorders(selection) {
      _classPrivateFieldGet(this, _selectionBorders).get(selection).forEach(function (border) {
        return border.destroy();
      });
      _classPrivateFieldGet(this, _selectionBorders).delete(selection);
    }

    /**
     * Renders all the selections (add CSS classes to cells and draw borders).
     *
     * @param {boolean} fastDraw Indicates the render cycle type (fast/slow).
     */
  }, {
    key: "render",
    value: function render(fastDraw) {
      var _this = this;
      if (_classPrivateFieldGet(this, _selections) === null) {
        return;
      }
      if (fastDraw) {
        // there was no rerender, so we need to remove classNames by ourselves
        _classPrivateMethodGet(this, _resetCells, _resetCells2).call(this);
      }
      var selections = Array.from(_classPrivateFieldGet(this, _selections));
      var classNamesMap = new Map();
      var _loop = function _loop() {
        var selection = selections[i];
        var _selection$settings = selection.settings,
          className = _selection$settings.className,
          createLayers = _selection$settings.createLayers,
          selectionType = _selection$settings.selectionType;
        if (!_classPrivateFieldGet(_this, _destroyListeners).has(selection)) {
          _classPrivateFieldGet(_this, _destroyListeners).add(selection);
          selection.addLocalHook('destroy', function () {
            return _this.destroyBorders(selection);
          });
        }
        var borderInstance = _this.getBorderInstance(selection);
        if (selection.isEmpty()) {
          borderInstance === null || borderInstance === void 0 ? void 0 : borderInstance.disappear();
          return "continue"; // eslint-disable-line no-continue
        }
        if (className) {
          var elements = _classPrivateFieldGet(_this, _scanner).setActiveSelection(selection).scan();
          elements.forEach(function (element) {
            if (classNamesMap.has(element)) {
              var classNamesLayers = classNamesMap.get(element);
              if (classNamesLayers.has(className) && createLayers === true) {
                classNamesLayers.set(className, classNamesLayers.get(className) + 1);
              } else {
                classNamesLayers.set(className, 1);
              }
            } else {
              classNamesMap.set(element, new Map([[className, 1]]));
            }
          });
        }
        var corners = selection.getCorners();
        _classPrivateFieldGet(_this, _activeOverlaysWot).getSetting('onBeforeDrawBorders', corners, selectionType);
        borderInstance === null || borderInstance === void 0 ? void 0 : borderInstance.appear(corners);
      };
      for (var i = 0; i < selections.length; i++) {
        var _ret = _loop();
        if (_ret === "continue") continue;
      }
      classNamesMap.forEach(function (classNamesLayers, element) {
        var classNames = Array.from(classNamesLayers).map(function (_ref) {
          var _ref2 = _slicedToArray(_ref, 2),
            className = _ref2[0],
            occurrenceCount = _ref2[1];
          if (occurrenceCount === 1) {
            return className;
          }
          return [className].concat(_toConsumableArray(Array.from({
            length: occurrenceCount - 1
          }, function (_, i) {
            return "".concat(className, "-").concat(i + 1);
          })));
        }).flat();
        classNames.forEach(function (className) {
          return _classPrivateFieldGet(_this, _appliedClasses).get(_classPrivateFieldGet(_this, _activeOverlaysWot)).add(className);
        });
        addClass(element, classNames);
      });
    }
  }]);
  return SelectionManager;
}();
function _resetCells2() {
  var _this2 = this;
  var appliedOverlaysClasses = _classPrivateFieldGet(this, _appliedClasses).get(_classPrivateFieldGet(this, _activeOverlaysWot));
  var classesToRemove = _classPrivateFieldGet(this, _activeOverlaysWot).wtSettings.getSetting('onBeforeRemoveCellClassNames');
  if (Array.isArray(classesToRemove)) {
    for (var i = 0; i < classesToRemove.length; i++) {
      appliedOverlaysClasses.add(classesToRemove[i]);
    }
  }
  appliedOverlaysClasses.forEach(function (className) {
    var nodes = _classPrivateFieldGet(_this2, _activeOverlaysWot).wtTable.TABLE.querySelectorAll(".".concat(className));
    for (var _i2 = 0, len = nodes.length; _i2 < len; _i2++) {
      removeClass(nodes[_i2], className);
    }
  });
  appliedOverlaysClasses.clear();
}