"use strict";

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.tableWidthKey = exports.autoFillTableWidth = exports.FILL_COLUMN_CODE = void 0;

var _find = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/find"));

var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));

var _splice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/splice"));

var _calculations = require("../../base/calculations");

var _utils = require("../../utils");

var _styles = require("../../base/styles");

var FILL_COLUMN_CODE = '$_fill_column_&';
exports.FILL_COLUMN_CODE = FILL_COLUMN_CODE;
var tableWidthKey = 'tableWidth';
exports.tableWidthKey = tableWidthKey;
var fillColumnWidthKey = 'fillColumnWidth';

var autoFillTableWidth = function autoFillTableWidth() {
  return function (pipeline) {
    var width = pipeline.getStateAtKey(fillColumnWidthKey, 0);
    var columns = pipeline.getColumns();
    var fillColumns = (0, _find.default)(columns).call(columns, function (col) {
      return col.code === FILL_COLUMN_CODE;
    });

    if (fillColumns) {
      fillColumns.width = width;
    } else {
      var rightNestedLockCount = (0, _calculations.getLeftNestedLockCount)((0, _slice.default)(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: _styles.Classes.emptyColCell
          };
        }
      };
      (0, _splice.default)(columns).call(columns, spliceIndex || columns.length, 0, _fillColumns);
    }

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

exports.autoFillTableWidth = autoFillTableWidth;

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

    if ((0, _utils.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);
  }
};