'use strict';

var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
var _createClass = require('@babel/runtime/helpers/createClass');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
var index = require('./index-7d6992d6.js');
var DivaUtils = require('@crystaldesign/diva-utils');
require('@babel/runtime/helpers/slicedToArray');
require('@babel/runtime/helpers/objectWithoutProperties');
require('axios');
require('@crystaldesign/basket-model');
require('@crystaldesign/basket-handler');
require('socket.io-client');
require('@babel/runtime/helpers/typeof');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _asyncToGenerator__default = /*#__PURE__*/_interopDefaultLegacy(_asyncToGenerator);
var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);
var DivaUtils__default = /*#__PURE__*/_interopDefaultLegacy(DivaUtils);

var ShelfPlanner = /*#__PURE__*/function () {
  function ShelfPlanner(data, article) {
    _classCallCheck__default["default"](this, ShelfPlanner);
    //article of the shelfplanner
    _defineProperty__default["default"](this, "article", void 0);
    //grids of the shelfplanner.
    _defineProperty__default["default"](this, "grids", []);
    //can be hidden if showOnRule == false
    _defineProperty__default["default"](this, "isVisible", undefined);
    _defineProperty__default["default"](this, "showOnRule", void 0);
    //positioning in the configTree
    _defineProperty__default["default"](this, "showAfterOPT", void 0);
    //json from the J3D field of the article
    _defineProperty__default["default"](this, "data", void 0);
    //dictionary of all the accessoires with their quantity which can be free in theory  (eg: Jutzer Kleiderstange)
    _defineProperty__default["default"](this, "freeArticlesPossible", {});
    //dictionary of all the accessoires with their quantity which are currently free
    _defineProperty__default["default"](this, "freeArticlesPlanned", {});
    //rule on shelfAccessoires that defines certian cells on the accessoire can only be place (eg: T-Stück has to be placed on the ground)
    _defineProperty__default["default"](this, "gridAllowedOnCells", void 0);
    //rule of shelfaccessoires that restrics the accessoire to be placed only on other specific accessoires
    _defineProperty__default["default"](this, "gridAllowedOntoArticles", void 0);
    //rule in the shelfAccessoires that says if the accessoires is placed on the other grids of the parent aswell (eg: Jutzer Kleiderstange)
    _defineProperty__default["default"](this, "takePlaceOnOtherGrids", void 0);
    //rule so the shelfplanner cells get disabled when the neighbour (AVL or AVR) is smaller. eg: Ben sulvag
    _defineProperty__default["default"](this, "disableCellsByElement", void 0);
    _defineProperty__default["default"](this, "montageOptions", []);
    this.article = article;
    this.disableCellsByElement = data.DisableCells;
    this.data = data;
    this.showAfterOPT = data.ShowAfterOPT;
    this.showOnRule = data.ShowOnRule ? DivaUtils__default["default"].getRuleByFormula(data.ShowOnRule, article.catalogCodex, article.CatalogData.multiselectOptions) : undefined;
    this.gridAllowedOnCells = data.GridAllowedOnCells;
    this.gridAllowedOntoArticles = data.GridAllowedOntoArticles;
    this.takePlaceOnOtherGrids = data.TakePlaceOnOtherGrids;
    this.initFreeArticles();
    if (data.ShelfPlanner && data.ShelfPlanner.length > 0) {
      for (var i = 0; i < data.ShelfPlanner.length; i++) {
        this.creatNewGrid(i);
        this.updateDisabledCells();
      }
      this.montageOptions = _toConsumableArray__default["default"](new Set(this.grids.reduce(function (options, g) {
        options = options.concat(g.montageOptionsList);
        return options;
      }, [])));
    }
  }

  /**
   *  init dictionary of all the accessoires that which can be free in theory
   */
  return _createClass__default["default"](ShelfPlanner, [{
    key: "initFreeArticles",
    value: function initFreeArticles() {
      if (!this.data.ShelfPlanner) return;
      for (var i = 0; i < this.data.ShelfPlanner.length; i++) {
        var grid = this.data.ShelfPlanner[i];
        if (!grid.initAccArr) continue;
        for (var j = 0; j < grid.initAccArr.length; j++) {
          var initAcc = grid.initAccArr[j];
          if (initAcc.noPrice) {
            if (this.freeArticlesPossible[initAcc.Codex] === undefined) this.freeArticlesPossible[initAcc.Codex] = 0;
            this.freeArticlesPossible[initAcc.Codex] += initAcc.Quantity;
          }
        }
      }
    }
  }, {
    key: "IsVisible",
    get: function get() {
      return this.isVisible;
    }
    /**
     * if the shelfplanner step was not visible but is visible again the initAcc get initialized but only if !this.article.shelfPlanData -> the shelfplanner get initialized from basket
     * if the shelfplanner step is no more visible delete all the accessoires
     * @param isVisible new value
     */
  }, {
    key: "setIsVisible",
    value: (function () {
      var _setIsVisible = _asyncToGenerator__default["default"](/*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee(isVisible) {
        return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              if (!(this.isVisible != isVisible)) {
                _context.next = 12;
                break;
              }
              if (!isVisible) {
                _context.next = 10;
                break;
              }
              this.isVisible = isVisible;
              if (this.article.shelfPlanData) {
                _context.next = 8;
                break;
              }
              _context.next = 6;
              return this.onConfigChanged({});
            case 6:
              _context.next = 8;
              return this.initAccList();
            case 8:
              _context.next = 12;
              break;
            case 10:
              _context.next = 12;
              return this.deleteAllAcc();
            case 12:
              this.isVisible = isVisible;
            case 13:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function setIsVisible(_x) {
        return _setIsVisible.apply(this, arguments);
      }
      return setIsVisible;
    }()
    /**
     * if the config is changed and the grid gets new height / accessories a new grid gets created
     */
    )
  }, {
    key: "onConfigChanged",
    value: (function () {
      var _onConfigChanged = _asyncToGenerator__default["default"](/*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2(variantValues) {
        var newHeightSet, gridsTodos, i, _i, _i2, grid, grids, _i3, _grid$DisableCellsByM, _grid;
        return _regeneratorRuntime__default["default"].wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              newHeightSet = false;
              gridsTodos = [];
              for (i = 0; i < this.grids.length; i++) {
                gridsTodos.push(this.grids[i].onConfigChanged());
              }
              //first delete all disables grids then init all the new ones
              _i = 0;
            case 4:
              if (!(_i < gridsTodos.length)) {
                _context2.next = 11;
                break;
              }
              if (!gridsTodos[_i].length) {
                _context2.next = 8;
                break;
              }
              _context2.next = 8;
              return this.grids[_i].deleteAllAccOfGrid();
            case 8:
              _i++;
              _context2.next = 4;
              break;
            case 11:
              _i2 = 0;
            case 12:
              if (!(_i2 < gridsTodos.length)) {
                _context2.next = 23;
                break;
              }
              if (gridsTodos[_i2].length) {
                _context2.next = 15;
                break;
              }
              return _context2.abrupt("continue", 20);
            case 15:
              grid = this.grids[_i2];
              if (gridsTodos[_i2].includes('heightGridRule')) {
                this.creatNewGrid(_i2);
                newHeightSet = true;
              }
              if (!((gridsTodos[_i2].includes('heightGridRule') || gridsTodos[_i2].includes('disableGridRule')) && !grid.DisabledByRule)) {
                _context2.next = 20;
                break;
              }
              _context2.next = 20;
              return this.initAccList(_i2);
            case 20:
              _i2++;
              _context2.next = 12;
              break;
            case 23:
              if (!(!newHeightSet && Object.keys(variantValues).length)) {
                _context2.next = 34;
                break;
              }
              grids = this.activeGrids;
              _i3 = 0;
            case 26:
              if (!(_i3 < grids.length)) {
                _context2.next = 34;
                break;
              }
              _grid = grids[_i3];
              if (!((_grid$DisableCellsByM = _grid.DisableCellsByMeasures) !== null && _grid$DisableCellsByM !== void 0 && _grid$DisableCellsByM.options.find(function (o) {
                return Object.keys(variantValues).includes('OPT' + o.opt);
              }) || !!_grid.disableCellsByRules)) {
                _context2.next = 31;
                break;
              }
              newHeightSet = true;
              return _context2.abrupt("break", 34);
            case 31:
              _i3++;
              _context2.next = 26;
              break;
            case 34:
              if (newHeightSet) {
                this.updateDisabledCells();
              }
            case 35:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function onConfigChanged(_x2) {
        return _onConfigChanged.apply(this, arguments);
      }
      return onConfigChanged;
    }())
  }, {
    key: "creatNewGrid",
    value: function creatNewGrid(i) {
      this.grids[i] = new index.Grid(i, this.article, this.data);
    }

    /**
     * runs through the InitAccArr and initialized all the accessoires eg: Kleiderstange gets placed
     * if the replaceFromParent == true it removed the same article from the parent shelfplanner if one is found  eg: Kleiderstange gets removed from schrank when the T-Sück gets initialized
     */
  }, {
    key: "initAccList",
    value: (function () {
      var _initAccList = _asyncToGenerator__default["default"](/*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee3(gridIndex) {
        var grids, i, grid, j, initAcc, k, _this$article$accesso, shelfId, accessoires, _accessoireToDelete$s, accessoireToDelete, rh;
        return _regeneratorRuntime__default["default"].wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              grids = this.activeGrids;
              i = 0;
            case 2:
              if (!(i < grids.length)) {
                _context3.next = 36;
                break;
              }
              grid = grids[i];
              if (!(gridIndex !== undefined && grid.ShelfIndex !== gridIndex)) {
                _context3.next = 6;
                break;
              }
              return _context3.abrupt("continue", 33);
            case 6:
              if (grid.InitAccArr) {
                _context3.next = 8;
                break;
              }
              return _context3.abrupt("continue", 33);
            case 8:
              j = 0;
            case 9:
              if (!(j < grid.InitAccArr.length)) {
                _context3.next = 33;
                break;
              }
              initAcc = grid.InitAccArr[j];
              k = 0;
            case 12:
              if (!(k < initAcc.initRH.length)) {
                _context3.next = 30;
                break;
              }
              grid.ActAccessoire = initAcc.Codex;
              _context3.next = 16;
              return index.setHandlerInstance.addAccessorieOnShelfPlanner(this.article.set, grid.ShelfIndex, initAcc.initRH[k], grid.basketId, {
                noMove: initAcc.noMove,
                noDelete: initAcc.noDelete,
                byInit: true
              });
            case 16:
              if (!initAcc.replaceFromParent) {
                _context3.next = 26;
                break;
              }
              shelfId = this.getShelfParentShelfId();
              if (!(shelfId && (_this$article$accesso = this.article.accessoireParentArticle) !== null && _this$article$accesso !== void 0 && _this$article$accesso.shelfPlanner)) {
                _context3.next = 26;
                break;
              }
              accessoires = this.article.accessoireParentArticle.shelfPlanner.getAccessorireByCodex(shelfId, initAcc.Codex);
              if (!(accessoires && accessoires.length > 0)) {
                _context3.next = 26;
                break;
              }
              accessoireToDelete = accessoires[0];
              rh = (_accessoireToDelete$s = accessoireToDelete.shelfPlanner) === null || _accessoireToDelete$s === void 0 ? void 0 : _accessoireToDelete$s.getRHOnParentArticle();
              if (!(rh !== undefined && accessoireToDelete.relatedToShelfGrid !== undefined)) {
                _context3.next = 26;
                break;
              }
              _context3.next = 26;
              return index.setHandlerInstance.deleteAccessorieOnShelfPlanner(this.article.set, accessoireToDelete.relatedToShelfGrid, rh, this.article.accessoireParentArticle.basketId);
            case 26:
              grid.ActAccessoire = undefined;
            case 27:
              k++;
              _context3.next = 12;
              break;
            case 30:
              j++;
              _context3.next = 9;
              break;
            case 33:
              i++;
              _context3.next = 2;
              break;
            case 36:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function initAccList(_x3) {
        return _initAccList.apply(this, arguments);
      }
      return initAccList;
    }()
    /**
     * finds all the accessoires of one grid by articleCodex
     * @param shelfId
     * @param articleCodex
     * @returns
     */
    )
  }, {
    key: "getAccessorireByCodex",
    value: function getAccessorireByCodex(shelfId, articleCodex) {
      var grid = this.grids.find(function (grid) {
        return grid.ShelfId == shelfId;
      });
      var accessoires = [];
      if (grid) {
        for (var key in grid.Accessoires) {
          if (grid.Accessoires[key].articleCodex == articleCodex) accessoires.push(grid.Accessoires[key]);
        }
      }
      return accessoires;
    }
  }, {
    key: "triggerVisibility",
    value: function () {
      var _triggerVisibility = _asyncToGenerator__default["default"](/*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee4(gridGroup) {
        var toCleanOptions, toUpdateOptions, i, grid, _i4, option, visitOptionState;
        return _regeneratorRuntime__default["default"].wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              toCleanOptions = [];
              toUpdateOptions = [];
              i = 0;
            case 3:
              if (!(i < this.grids.length)) {
                _context4.next = 13;
                break;
              }
              grid = this.grids[i];
              if (grid.VisitOption) {
                _context4.next = 7;
                break;
              }
              return _context4.abrupt("continue", 10);
            case 7:
              if (!(toUpdateOptions.includes(grid.VisitOption) || toCleanOptions.includes(grid.VisitOption))) {
                _context4.next = 9;
                break;
              }
              return _context4.abrupt("continue", 10);
            case 9:
              if (gridGroup && (grid.gridGroup == gridGroup || grid.alternativeGridGroups.includes(gridGroup))) {
                toUpdateOptions.push(grid.VisitOption);
                if (toCleanOptions.includes(grid.VisitOption)) toCleanOptions.splice(toCleanOptions.indexOf(grid.VisitOption), 1);
              } else {
                toCleanOptions.push(grid.VisitOption);
              }
            case 10:
              i++;
              _context4.next = 3;
              break;
            case 13:
              _i4 = 0;
            case 14:
              if (!(_i4 < [].concat(toUpdateOptions, toCleanOptions).length)) {
                _context4.next = 23;
                break;
              }
              option = [].concat(toUpdateOptions, toCleanOptions)[_i4];
              visitOptionState = this.article.getArticleOptionState((!this.article.CatalogData.isIDMFormat ? 'OPT' : '') + option);
              if (!visitOptionState) {
                _context4.next = 20;
                break;
              }
              _context4.next = 20;
              return index.articleHandlerInstance.updateOption(this.article, visitOptionState.optionCodex, toUpdateOptions.includes(option) ? 'OPVMIT' : 'OPVOHNE');
            case 20:
              _i4++;
              _context4.next = 14;
              break;
            case 23:
            case "end":
              return _context4.stop();
          }
        }, _callee4, this);
      }));
      function triggerVisibility(_x4) {
        return _triggerVisibility.apply(this, arguments);
      }
      return triggerVisibility;
    }()
  }, {
    key: "deleteAllAcc",
    value: function () {
      var _deleteAllAcc = _asyncToGenerator__default["default"](/*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee5() {
        var i;
        return _regeneratorRuntime__default["default"].wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              this.article.shelfPlanData = undefined;
              i = 0;
            case 2:
              if (!(i < this.grids.length)) {
                _context5.next = 8;
                break;
              }
              _context5.next = 5;
              return this.grids[i].deleteAllAccOfGrid();
            case 5:
              i++;
              _context5.next = 2;
              break;
            case 8:
            case "end":
              return _context5.stop();
          }
        }, _callee5, this);
      }));
      function deleteAllAcc() {
        return _deleteAllAcc.apply(this, arguments);
      }
      return deleteAllAcc;
    }()
  }, {
    key: "GridAllowedOnCells",
    get: function get() {
      return this.gridAllowedOnCells;
    }
  }, {
    key: "GridAllowedOntoArticles",
    get: function get() {
      return this.gridAllowedOntoArticles;
    }
  }, {
    key: "TakePlaceOnOtherGrids",
    get: function get() {
      return this.takePlaceOnOtherGrids;
    }

    /**
     * its checked if the accessoire has place on a specific grid  on a specific cell
     * if the accessoire doesTakePlaceOnOtherGrids == true then we must check on the other grids aswell if there is place
     * @param gridIndex specific grid
     * @param cellIndex specific cell
     * @param accessoire
     * @returns
     */
  }, {
    key: "tryFitOnShelfOfGrid",
    value: function tryFitOnShelfOfGrid(gridIndex, cellIndex, accessoire) {
      var size = accessoire.shelfHeight;
      var grid = this.grids[gridIndex];
      if (!size || isNaN(size)) {
        alert('Der artikel: ' + accessoire.name + " hat keine RH hinterlegt! Der Metatag 'HEIGHTGRIDUSED' ist: " + accessoire.shelfHeight);
        return false;
      } else {
        var ret = false;
        var grids = this.doesTakePlaceOnOtherGrids(accessoire) ? this.activeGrids : [grid];
        if (grid.checkAccessoireInGridRules(accessoire)) {
          return {
            type: 'notAllowedByMaxQuantityReached',
            size: size
          };
        }
        for (var i = 0; i < grids.length; i++) {
          ret = grids[i].tryFitOnShelf(accessoire, cellIndex, accessoire.shelfPlanner);
          if (ret === false || ret.type === 'doesNotFit' || ret.type.startsWith('notAllowed') || ret.index === undefined) return ret;
        }
        return ret;
      }
    }

    /**
     *
     * @param gridName
     * @param accessoire
     * @param excludeAccessoireInfluence for the drag and drop usecase we need to calc all the free grids with exluding the moving accessoire
     * @returns
     */
  }, {
    key: "getFreeSpacesOfAccessoireOfGrids",
    value: function getFreeSpacesOfAccessoireOfGrids(gridName, accessoire) {
      var grids = this.grids; //this.GridsOrGroupById(gridName);

      var ret = {};
      for (var i = 0; i < grids.length; i++) {
        var grid = grids[i];
        if (grid.DisabledByRule) continue;
        ret[grid.GridName] = {
          freeCells: grid.getFreeSpacesOfAccessoire(accessoire),
          idx: i
        };
      }
      return ret;
    }
  }, {
    key: "getPlannedSpacesOfGrids",
    value: function getPlannedSpacesOfGrids() {
      var grids = this.grids;
      var ret = {};
      for (var i = 0; i < grids.length; i++) {
        var grid = grids[i];
        if (grid.DisabledByRule) continue;
        ret[grid.GridName] = {
          accessories: grid.getPlannedSpaces(),
          idx: i
        };
      }
      return ret;
    }

    /**
     * delete specific accessoire in the grid
     * @param gridIndex
     * @param cellIndex
     * @returns
     */
  }, {
    key: "deleteAccessoireOfCellInGrid",
    value: (function () {
      var _deleteAccessoireOfCellInGrid = _asyncToGenerator__default["default"](/*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee6(gridIndex, cellIndex) {
        var grid, inUse, deleteIndex, onBoardCell, accessoire;
        return _regeneratorRuntime__default["default"].wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              grid = this.grids[gridIndex];
              inUse = grid.Cells[cellIndex].InUse;
              onBoardCell = grid.Cells.find(function (cell) {
                return cell.OnBoard == inUse;
              });
              if (onBoardCell) {
                deleteIndex = onBoardCell.InUse;
                onBoardCell.Article;
              } else {
                deleteIndex = cellIndex;
                accessoire = grid.Cells[cellIndex].Article;
              }
              if (!accessoire) {
                _context6.next = 8;
                break;
              }
              this.checkForNewFreeAccessoire(accessoire, gridIndex);
              _context6.next = 8;
              return this.handleDeleteTakePlaceOnOtherGrids(gridIndex, deleteIndex, accessoire);
            case 8:
              _context6.next = 10;
              return grid.deleteAccessoireInCells(deleteIndex);
            case 10:
              return _context6.abrupt("return", _context6.sent);
            case 11:
            case "end":
              return _context6.stop();
          }
        }, _callee6, this);
      }));
      function deleteAccessoireOfCellInGrid(_x5, _x6) {
        return _deleteAccessoireOfCellInGrid.apply(this, arguments);
      }
      return deleteAccessoireOfCellInGrid;
    }()
    /**
     * if the deleted accessoire was free (no price) check if another existing one can now become free
     * @param accessoire
     * @param gridIndex
     */
    )
  }, {
    key: "checkForNewFreeAccessoire",
    value: function checkForNewFreeAccessoire(accessoire, gridIndex) {
      if (this.freeArticlesPossible[accessoire.articleCodex] !== undefined && accessoire.noPrice) {
        this.freeArticlesPlanned[accessoire.articleCodex] -= accessoire.quantity;
        // find now an already planned article which can get the noPrice true
        var grid = this.grids[gridIndex];
        for (var key in grid.Accessoires) {
          if (grid.Accessoires[key].articleCodex == accessoire.articleCodex && !grid.Accessoires[key].noPrice) {
            grid.Accessoires[key].noPrice = true;
            this.freeArticlesPlanned[grid.Accessoires[key].articleCodex] += accessoire.quantity;
          }
        }
      }
    }
    /**
     * clears all the placeholders of other grids if the accessorie TakePlaceOnOtherGrids == true
     * @param gridIndex
     * @param cellIndex
     * @param accessoire
     */
  }, {
    key: "handleDeleteTakePlaceOnOtherGrids",
    value: (function () {
      var _handleDeleteTakePlaceOnOtherGrids = _asyncToGenerator__default["default"](/*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee7(gridIndex, cellIndex, accessoire) {
        var i, _cell$Article, cell, _i5, _cell$Article2, _cell, _i6;
        return _regeneratorRuntime__default["default"].wrap(function _callee7$(_context7) {
          while (1) switch (_context7.prev = _context7.next) {
            case 0:
              if (accessoire.shelfHeight) {
                _context7.next = 2;
                break;
              }
              return _context7.abrupt("return");
            case 2:
              if (accessoire.shelfHeightAbove) {
                for (i = 0; i < accessoire.shelfHeightAbove; i++) {
                  cell = this.grids[gridIndex].Cells[cellIndex + accessoire.shelfHeight + i];
                  if ((cell === null || cell === void 0 || (_cell$Article = cell.Article) === null || _cell$Article === void 0 ? void 0 : _cell$Article.basketId) === accessoire.basketId) {
                    cell.ClearInUse();
                  }
                }
              }
              if (accessoire.shelfHeightBelow) {
                for (_i5 = 0; _i5 < accessoire.shelfHeightBelow; _i5++) {
                  _cell = this.grids[gridIndex].Cells[cellIndex - (_i5 + 1)];
                  if ((_cell === null || _cell === void 0 || (_cell$Article2 = _cell.Article) === null || _cell$Article2 === void 0 ? void 0 : _cell$Article2.basketId) === accessoire.basketId) {
                    _cell.ClearInUse();
                  }
                }
              }
              if (!this.doesTakePlaceOnOtherGrids(accessoire)) {
                _context7.next = 14;
                break;
              }
              _i6 = 0;
            case 6:
              if (!(_i6 < this.grids.length)) {
                _context7.next = 14;
                break;
              }
              if (!(_i6 === gridIndex)) {
                _context7.next = 9;
                break;
              }
              return _context7.abrupt("continue", 11);
            case 9:
              _context7.next = 11;
              return this.grids[_i6].deleteAccessoireInCells(cellIndex);
            case 11:
              _i6++;
              _context7.next = 6;
              break;
            case 14:
            case "end":
              return _context7.stop();
          }
        }, _callee7, this);
      }));
      function handleDeleteTakePlaceOnOtherGrids(_x7, _x8, _x9) {
        return _handleDeleteTakePlaceOnOtherGrids.apply(this, arguments);
      }
      return handleDeleteTakePlaceOnOtherGrids;
    }()
    /**
     * accessoire gets planned on a grid in a specific cellIndex which was already controlled if it fits there via function tryFitOnShelfOfGrid
     * @param accessoire
     * @param gridIndex
     * @param cellIndex
     * @param type
     */
    )
  }, {
    key: "addAccessoireInCellInGrid",
    value: (function () {
      var _addAccessoireInCellInGrid = _asyncToGenerator__default["default"](/*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee8(accessoire, gridIndex, cellIndex, type, params) {
        var grids, i, grid;
        return _regeneratorRuntime__default["default"].wrap(function _callee8$(_context8) {
          while (1) switch (_context8.prev = _context8.next) {
            case 0:
              grids = this.doesTakePlaceOnOtherGrids(accessoire) ? this.activeGrids : [this.grids[gridIndex]];
              i = 0;
            case 2:
              if (!(i < grids.length)) {
                _context8.next = 11;
                break;
              }
              grid = grids[i];
              if (!grid.DisabledByRule) {
                _context8.next = 6;
                break;
              }
              return _context8.abrupt("continue", 8);
            case 6:
              _context8.next = 8;
              return grids[i].addAccessoireInCells(cellIndex, accessoire, type, grid.ShelfIndex !== gridIndex ? true : params === null || params === void 0 ? void 0 : params.noMove, grid.ShelfIndex !== gridIndex ? true : params === null || params === void 0 ? void 0 : params.noDelete, grid.ShelfIndex !== gridIndex ? true : undefined);
            case 8:
              i++;
              _context8.next = 2;
              break;
            case 11:
              this.checkForFreeAccessoire(accessoire);
            case 12:
            case "end":
              return _context8.stop();
          }
        }, _callee8, this);
      }));
      function addAccessoireInCellInGrid(_x10, _x11, _x12, _x13, _x14) {
        return _addAccessoireInCellInGrid.apply(this, arguments);
      }
      return addAccessoireInCellInGrid;
    }()
    /**
     * check if new accessoire can be free
     * @param accessoire
     */
    )
  }, {
    key: "checkForFreeAccessoire",
    value: function checkForFreeAccessoire(accessoire) {
      if (this.freeArticlesPossible[accessoire.articleCodex] !== undefined) {
        if (this.freeArticlesPlanned[accessoire.articleCodex] === undefined || this.freeArticlesPossible[accessoire.articleCodex] > this.freeArticlesPlanned[accessoire.articleCodex]) {
          accessoire.noPrice = true;
          if (this.freeArticlesPlanned[accessoire.articleCodex] === undefined) this.freeArticlesPlanned[accessoire.articleCodex] = 0;
          this.freeArticlesPlanned[accessoire.articleCodex] += accessoire.quantity;
        }
      }
    }
    /**
     * checks if the accessoire should TakePlaceOnOtherGrids
     * @param takePlaceOnOtherGrids
     * @returns
     */
  }, {
    key: "doesTakePlaceOnOtherGrids",
    value: function doesTakePlaceOnOtherGrids(artice) {
      var _artice$shelfPlanner;
      var takePlaceOnOtherGrids = (_artice$shelfPlanner = artice.shelfPlanner) === null || _artice$shelfPlanner === void 0 ? void 0 : _artice$shelfPlanner.takePlaceOnOtherGrids;
      if (takePlaceOnOtherGrids) {
        for (var i = 0; i < takePlaceOnOtherGrids.length; i++) {
          if (takePlaceOnOtherGrids[i].onParent == this.article.articleCodex) {
            return true;
          }
        }
      }
      return false;
    }
  }, {
    key: "accessoires",
    get: function get() {
      var accessoires = {};
      var grids = this.activeGrids;
      for (var i = 0; i < grids.length; i++) {
        for (var key in grids[i].Accessoires) {
          accessoires[key] = grids[i].Accessoires[key];
        }
      }
      return Object.keys(accessoires).length > 0 ? accessoires : undefined;
    }
  }, {
    key: "DisableCellsByElement",
    get: function get() {
      return this.disableCellsByElement;
    }
  }, {
    key: "getActAccessoireOfGrid",
    value: function getActAccessoireOfGrid(index) {
      return this.grids[index].ActAccessoire;
    }
  }, {
    key: "setActAccessoireOfGrid",
    value: function setActAccessoireOfGrid(gridName, articleCodex) {
      var somethingChanged = false;
      var grids = this.GridsOrGroupById(gridName);
      for (var i = 0; i < grids.length; i++) {
        var grid = grids[i];
        if (articleCodex && grid.getArticleRelationsById(gridName).includes(articleCodex)) {
          if (grid.ActAccessoire !== articleCodex) {
            grid.ActAccessoire = articleCodex;
            somethingChanged = true;
          }
        } else grid.ActAccessoire = undefined;
      }
      return somethingChanged;
    }

    /**
     * values that get saved in the basket to re-initialize the shelf
     * @returns
     */
  }, {
    key: "generateShelfPlandata",
    value: function generateShelfPlandata() {
      var _this$article$doorPla;
      var ret = [];
      var grids = this.activeGrids;
      for (var i = 0; i < grids.length; i++) {
        var cells = [];
        var grid = grids[i];
        for (var j = 0; j < grid.Cells.length; j++) {
          var cell = grid.Cells[j];
          cells.push({
            inUse: cell.InUse,
            noDelete: cell.NoDelete,
            noMove: cell.NoMove,
            onBoard: cell.OnBoard
          });
          if (grid.ShelfIndex != i) cells[j].gridIndex = grid.ShelfIndex;
          if (cell.InUse == j) {
            var _cell$Article3, _cell$Article4;
            cells[j].usedArticleData = {
              Codex: (_cell$Article3 = cell.Article) === null || _cell$Article3 === void 0 ? void 0 : _cell$Article3.articleCodex,
              BasketID: (_cell$Article4 = cell.Article) === null || _cell$Article4 === void 0 ? void 0 : _cell$Article4.basketId
            };
          }
        }
        ret.push(cells);
      }
      return {
        ShelfPlanner2: ret,
        DoorPlannerData: (_this$article$doorPla = this.article.doorPlanner) === null || _this$article$doorPla === void 0 ? void 0 : _this$article$doorPla.getMovedData(this.article.basketId)
      };
    }

    /**
     * collecting all the information that is needed for the 3D exe
     * @param accessoires
     * @returns
     */
  }, {
    key: "getShelfPlannerAccessoires3DValues",
    value: function getShelfPlannerAccessoires3DValues(accessoires) {
      var grids = this.activeGrids;
      for (var i = 0; i < grids.length; i++) {
        var grid = grids[i];
        for (var j = 0; j < grid.Cells.length; j++) {
          var cell = grid.Cells[j];
          if (cell.InUse == j && cell.Article && cell.Article.model3DName && !cell.OnlyPlaceHolder) {
            var _cell$Article5;
            var cellIndex = cell.Index;
            if (grid.Direction == 'vertikal' && this.article.CatalogData.useShelfPlannerRTV != true) {
              cellIndex = grid.Cells.length - 1 - cell.Index;
            }
            accessoires.push({
              basketId: (_cell$Article5 = cell.Article) === null || _cell$Article5 === void 0 ? void 0 : _cell$Article5.basketId,
              gridId: grid.ShelfIndex,
              gridName: grid.GridName,
              model: cell.Article.model3DName,
              parentBasketId: this.article.basketId,
              parentElementId: this.getShelfElementId(),
              rh: cellIndex
            });
            if (cell.Article.shelfPlanner) accessoires = accessoires.concat(cell.Article.shelfPlanner.getShelfPlannerAccessoires3DValues([]));
          }
        }
      }
      return accessoires;
    }
    /**
     * return specific shelfElementId. works reqursive. Used to identify every grid on their parents and parents-parent etc. for the 3DValues
     * @returns
     */
  }, {
    key: "getShelfElementId",
    value: function getShelfElementId() {
      var _this$article$accesso2;
      if ((_this$article$accesso2 = this.article.accessoireParentArticle) !== null && _this$article$accesso2 !== void 0 && _this$article$accesso2.shelfPlanner && this.article.relatedToShelfGrid !== undefined && this.grids.length > 0) {
        var rh = this.getRHOnParentArticle();
        var parentId = this.article.accessoireParentArticle.shelfPlanner.getShelfElementId();
        return parentId + '.' + this.article.relatedToShelfGrid + '.' + rh;
      } else {
        return this.article.elementId.toString();
      }
    }
    /**
     * return the index of the accessoire on which it is placed in the parent
     * @returns
     */
  }, {
    key: "getRHOnParentArticle",
    value: function getRHOnParentArticle() {
      var _this$article$accesso3,
        _this = this;
      if (this.article.relatedToShelfGrid === undefined) return undefined;
      return (_this$article$accesso3 = this.article.accessoireParentArticle) === null || _this$article$accesso3 === void 0 || (_this$article$accesso3 = _this$article$accesso3.shelfPlanner) === null || _this$article$accesso3 === void 0 || (_this$article$accesso3 = _this$article$accesso3.grids[this.article.relatedToShelfGrid].Cells.find(function (item) {
        var _item$Article;
        return ((_item$Article = item.Article) === null || _item$Article === void 0 ? void 0 : _item$Article.basketId) == _this.article.basketId;
      })) === null || _this$article$accesso3 === void 0 ? void 0 : _this$article$accesso3.InUse;
    }

    /**
     * retrun all the required values of the current selectable accessoires for the view
     * @param configStepKey
     * @returns
     */
  }, {
    key: "getShelfPlannerItems",
    value: function getShelfPlannerItems(configStepKey) {
      var accessoires = [];
      var catalogData = this.article.CatalogData;
      var grids = this.GridsOrGroupById(configStepKey);

      //check for grids that are in array because of articleRelationsForOtherGroups

      for (var j = 0; j < grids.length; j++) {
        var articleRelations = grids[j].getArticleRelationsById(configStepKey);
        if (articleRelations !== null && articleRelations !== void 0 && articleRelations.length) {
          var _loop = function _loop() {
            var articleCodex = articleRelations[i];
            if (catalogData.checkIfArticleCodexExists(articleCodex)) {
              var catalogArticle = catalogData.getCatalogArticleByArticleCodex(articleCodex);
              if (!catalogArticle || accessoires.find(function (a) {
                return a.articleCodex === catalogArticle.articleCodex;
              })) return 1; // continue
              accessoires.push({
                articleCodex: catalogArticle.articleCodex,
                configStepKeys: [],
                image: catalogArticle.image ? catalogData.getCatImageURL(catalogArticle.image, '') : undefined,
                name: catalogArticle.name,
                longDescription: catalogArticle.longDescription,
                price: !catalogData.dontShowBasePrice ? Number(catalogArticle.articlePrice) : 0,
                width: catalogArticle.width,
                height: catalogArticle.height,
                depth: catalogArticle.depth,
                cellSize: catalogArticle.shelfHeight,
                metaData: catalogArticle.metaDataView,
                contentItemId: catalogArticle.contentItemId,
                groupContentItemId: catalogArticle.groupContentItemId,
                partlistcodexes: catalogArticle.possiblePartlistCodexes
              });
            }
          };
          for (var i = 0; i < articleRelations.length; i++) {
            if (_loop()) continue;
          }
        }
      }
      return {
        accessoires: accessoires,
        grids: grids
      };
    }
    /**
     * helperfuntion to get the parentshelfId of an shelfPlanner eg: T-Stück
     * @returns
     */
  }, {
    key: "getShelfParentShelfId",
    value: function getShelfParentShelfId() {
      var _this$article$accesso4;
      if (this.article.relatedToShelfGrid !== undefined) return (_this$article$accesso4 = this.article.accessoireParentArticle) === null || _this$article$accesso4 === void 0 || (_this$article$accesso4 = _this$article$accesso4.shelfPlanner) === null || _this$article$accesso4 === void 0 || (_this$article$accesso4 = _this$article$accesso4.grids[this.article.relatedToShelfGrid]) === null || _this$article$accesso4 === void 0 ? void 0 : _this$article$accesso4.ShelfId;
      return undefined;
    }

    /**
     * if the dockingpoints get updated check updateDisabledCells
     * @param dpType
     */
  }, {
    key: "updateOnDockingChanged",
    value: function updateOnDockingChanged(dpType) {
      if (dpType == 'AVL' && this.disableCellsByElement == 'RH_OVER_AVL' || dpType == 'AVR' && this.disableCellsByElement == 'RH_OVER_AVR') this.updateDisabledCells();
    }

    /**
     * calls the update/check on itself and the docket article
     */
  }, {
    key: "updateDisabledCells",
    value: function updateDisabledCells() {
      this.updateDisabledCellsOnDockedElements();
      this.checkOnDockedHeight();
    }
  }, {
    key: "updateDisabledCellsOnDockedElements",
    value: function updateDisabledCellsOnDockedElements() {
      var grids = this.activeGrids;
      var dockedOnAVL = this.article.dockedOnAV('L');
      var dockedOnAVR = this.article.dockedOnAV('R');
      if (this.disableCellsByElement == 'RH_OVER_AVR' && dockedOnAVL) {
        var _dockedOnAVL$shelfPla;
        (_dockedOnAVL$shelfPla = dockedOnAVL.shelfPlanner) === null || _dockedOnAVL$shelfPla === void 0 || _dockedOnAVL$shelfPla.disableCellsByDockedShelfs(grids[0].getCellCount('AVL'));
      } else if (this.disableCellsByElement == 'RH_OVER_AVL' && dockedOnAVR) {
        var _dockedOnAVR$shelfPla;
        (_dockedOnAVR$shelfPla = dockedOnAVR.shelfPlanner) === null || _dockedOnAVR$shelfPla === void 0 || _dockedOnAVR$shelfPla.disableCellsByDockedShelfs(grids[0].getCellCount('AVR'));
      }
    }
  }, {
    key: "checkOnDockedHeight",
    value: function checkOnDockedHeight() {
      var dockedOnAVR = this.article.dockedOnAV('R');
      var dockedOnAVL = this.article.dockedOnAV('L');
      if (dockedOnAVR !== null && dockedOnAVR !== void 0 && dockedOnAVR.shelfPlanner && dockedOnAVR.shelfPlanner.activeGrids.length > 0 && this.disableCellsByElement == 'RH_OVER_AVR') {
        this.disableCellsByDockedShelfs(dockedOnAVR.shelfPlanner.activeGrids[0].getCellCount('AVL'));
      } else if (dockedOnAVL !== null && dockedOnAVL !== void 0 && dockedOnAVL.shelfPlanner && dockedOnAVL.shelfPlanner.activeGrids.length > 0 && this.disableCellsByElement == 'RH_OVER_AVL') {
        this.disableCellsByDockedShelfs(dockedOnAVL.shelfPlanner.activeGrids[0].getCellCount('AVR'));
      } else {
        this.disableCellsByDockedShelfs();
      }
    }

    /**
     * this function checks if cells are still disabled by a neighbour and updates them
     * @param count
     * @param fromDockSide
     */
  }, {
    key: "disableCellsByDockedShelfs",
    value: (function () {
      var _disableCellsByDockedShelfs = _asyncToGenerator__default["default"](/*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee9(count) {
        var grids, i, grid, gridCount, toDisableCells, useCount, j, _j, cell, _j2;
        return _regeneratorRuntime__default["default"].wrap(function _callee9$(_context9) {
          while (1) switch (_context9.prev = _context9.next) {
            case 0:
              grids = this.activeGrids;
              i = 0;
            case 2:
              if (!(i < grids.length)) {
                _context9.next = 29;
                break;
              }
              grid = grids[i];
              gridCount = grid.getCellCount();
              toDisableCells = grid.getDisabledCellsByRule();
              useCount = count == undefined || count > gridCount ? gridCount : count;
              for (j = useCount; j < grid.Cells.length; j++) {
                toDisableCells.push(j);
              }
              _j = 0;
            case 9:
              if (!(_j < toDisableCells.length)) {
                _context9.next = 18;
                break;
              }
              cell = grid.Cells[toDisableCells[_j]];
              if (!(cell.InUse == toDisableCells[_j])) {
                _context9.next = 14;
                break;
              }
              _context9.next = 14;
              return index.setHandlerInstance.deleteAccessorieOnShelfPlanner(this.article.set, grid.ShelfIndex, cell.InUse, grid.basketId);
            case 14:
              cell.IsDisabled = true;
            case 15:
              _j++;
              _context9.next = 9;
              break;
            case 18:
              _j2 = 0;
            case 19:
              if (!(_j2 < grid.Cells.length)) {
                _context9.next = 26;
                break;
              }
              if (!toDisableCells.includes(_j2)) {
                _context9.next = 22;
                break;
              }
              return _context9.abrupt("continue", 23);
            case 22:
              grid.Cells[_j2].IsDisabled = false;
            case 23:
              _j2++;
              _context9.next = 19;
              break;
            case 26:
              i++;
              _context9.next = 2;
              break;
            case 29:
            case "end":
              return _context9.stop();
          }
        }, _callee9, this);
      }));
      function disableCellsByDockedShelfs(_x15) {
        return _disableCellsByDockedShelfs.apply(this, arguments);
      }
      return disableCellsByDockedShelfs;
    }())
  }, {
    key: "getGridByGridName",
    value: function getGridByGridName(shelfId) {
      return this.grids.find(function (grid) {
        return grid.GridName == shelfId;
      });
    }
  }, {
    key: "getGridByIndex",
    value: function getGridByIndex(index) {
      return this.grids.find(function (grid) {
        return grid.ShelfIndex == index;
      });
    }
  }, {
    key: "GridsOrGroupById",
    value: function GridsOrGroupById(shelfId) {
      return this.activeGrids.filter(function (grid) {
        return grid.ShelfId == shelfId || grid.group == shelfId || grid.alternativeGridGroups.includes(shelfId);
      });
    }
  }, {
    key: "getSelectedAccessoireById",
    value: function getSelectedAccessoireById(shelfId) {
      var _grids$find;
      var grids = this.GridsOrGroupById(shelfId);
      return (_grids$find = grids.find(function (g) {
        if (g.ActAccessoire && g.getArticleRelationsById(shelfId).includes(g.ActAccessoire)) {
          return g;
        }
        return;
      })) === null || _grids$find === void 0 ? void 0 : _grids$find.ActAccessoire;
    }
  }, {
    key: "getCellIndexOfBasketId",
    value: function getCellIndexOfBasketId(gridIndex, basketId) {
      var _this$getGridByIndex;
      return (_this$getGridByIndex = this.getGridByIndex(gridIndex)) === null || _this$getGridByIndex === void 0 ? void 0 : _this$getGridByIndex.getIndexOfBasketId(basketId);
    }
  }, {
    key: "allGrids",
    get: function get() {
      return this.grids;
    }
    //all active grids. This is a intersection (schnittmenge) of the this.grids. Disables Grid by rulse are excluded
  }, {
    key: "activeGrids",
    get: function get() {
      return this.grids.filter(function (g) {
        return !g.DisabledByRule;
      });
    }
  }, {
    key: "allMontageOptions",
    get: function get() {
      return this.montageOptions;
    }
  }, {
    key: "getRelatedToGridIdByArticleCodex",
    value: function getRelatedToGridIdByArticleCodex(articleCodex, gridIndex) {
      var gridId = this.grids[gridIndex].getGridIdByArticleCodex(articleCodex);
      if (gridId) return gridId;
      for (var i = 0; i < this.grids.length; i++) {
        var _gridId = this.grids[i].getGridIdByArticleCodex(articleCodex);
        if (_gridId) return _gridId;
      }
      return undefined;
    }
  }]);
}();

exports["default"] = ShelfPlanner;
