import _findInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/find";
import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
import _spliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/splice";
import { getLeftNestedLockCount } from '../../base/calculations';
import { isLeafNode, makeRecursiveMapper } from '../../utils';
import { Classes } from '../../base/styles';
export var FILL_COLUMN_CODE = '$_fill_column_&';
export var tableWidthKey = 'tableWidth';
var fillColumnWidthKey = 'fillColumnWidth';
export var autoFillTableWidth = function autoFillTableWidth() {
  return function (pipeline) {
    var width = pipeline.getStateAtKey(fillColumnWidthKey, 0);
    var columns = pipeline.getColumns();

    var fillColumns = _findInstanceProperty(columns).call(columns, function (col) {
      return col.code === FILL_COLUMN_CODE;
    });

    if (fillColumns) {
      fillColumns.width = width;
    } else {
      var rightNestedLockCount = getLeftNestedLockCount(_sliceInstanceProperty(columns).call(columns).reverse());
      var spliceIndex = columns.length - rightNestedLockCount;
      var _fillColumns = {
        name: '',
        code: FILL_COLUMN_CODE,
        width: width,
        features: {
          resizeable: false
        },
        getCellProps: function getCellProps(value, record, rowIndex) {
          return {
            className: Classes.emptyColCell
          };
        }
      };

      _spliceInstanceProperty(columns).call(columns, spliceIndex || columns.length, 0, _fillColumns);
    }

    pipeline.columns(columns);
    setAutoFillWidth(pipeline);
    return pipeline;
  };
};

var setAutoFillWidth = function setAutoFillWidth(pipeline) {
  var tableWidth = pipeline.getStateAtKey(tableWidthKey);
  if (!tableWidth) return;
  var columnWidthSum = 0;
  pipeline.mapColumns(makeRecursiveMapper(function (col) {
    var width = col.width,
        code = col.code;

    if (isLeafNode(col) && code !== FILL_COLUMN_CODE) {
      var resizeColumn = pipeline.getStateAtKey('columnResize');
      columnWidthSum += resizeColumn && resizeColumn[code] || width;
    }

    return col;
  }));
  var fillColumnWidth = Math.floor(tableWidth - columnWidthSum);
  fillColumnWidth = fillColumnWidth > 0 ? fillColumnWidth : 0;
  var preWidth = pipeline.getStateAtKey(fillColumnWidthKey, 0);

  if (preWidth !== fillColumnWidth) {
    pipeline.setStateAtKey('fillColumnWidth', fillColumnWidth);
  }
};