import _extends from "@babel/runtime-corejs3/helpers/extends";
import { internals } from '../../internals';
import { isLeafNode, makeRecursiveMapper } from '../../utils';
function isIdentity(x, y) {
  return x === y;
}
export function autoRowSpan() {
  return function autoRowSpanStep(pipeline) {
    var dataSource = pipeline.getDataSource();
    return pipeline.mapColumns(makeRecursiveMapper(function (col, _ref) {
      var startIndex = _ref.startIndex,
        endIndex = _ref.endIndex;
      var _a;
      if (!((_a = col.features) === null || _a === void 0 ? void 0 : _a.autoRowSpan)) {
        return col;
      }
      if (!isLeafNode(col)) {
        return col;
      }
      var isFunc = typeof col.features.autoRowSpan === 'function';
      var shouldMergeCell = isFunc ? col.features.autoRowSpan : isIdentity;
      var spanRects = [];
      var lastBottom = 0;
      var prevValue = null;
      var prevRow = null;
      for (var rowIndex = 0; rowIndex < dataSource.length; rowIndex++) {
        var row = dataSource[rowIndex];
        var value = internals.safeGetValue(col, row, rowIndex);
        if (rowIndex === 0 || !shouldMergeCell(prevValue, value, prevRow, row)) {
          var spanRect = {
            top: lastBottom,
            bottom: rowIndex,
            left: startIndex,
            right: endIndex
          };
          for (var i = lastBottom; i < rowIndex; i++) {
            spanRects.push(spanRect);
          }
          lastBottom = rowIndex;
        }
        prevValue = value;
        prevRow = row;
      }
      for (var _i = lastBottom; _i < dataSource.length; _i++) {
        spanRects.push({
          top: lastBottom,
          bottom: dataSource.length,
          left: startIndex,
          right: endIndex
        });
      }
      return _extends(_extends({}, col), {
        getSpanRect: function getSpanRect(value, row, rowIndex) {
          return spanRects[rowIndex];
        }
      });
    }));
  };
}