"use strict";

exports.__esModule = true;
require("core-js/modules/es.array.push.js");
require("core-js/modules/es.array.at.js");
require("core-js/modules/es.error.cause.js");
var _constants = require("./constants");
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 _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
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 _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; } }
/**
 * @typedef {object} ViewportColumnsCalculatorOptions
 * @property {number} viewportWidth Width of the viewport.
 * @property {number} scrollOffset Current horizontal scroll position of the viewport.
 * @property {number} totalColumns Total number of columns.
 * @property {Function} columnWidthFn Function that returns the width of the column at a given index (in px).
 * @property {Function} overrideFn Function that changes calculated this.startRow, this.endRow (used by
 *   MergeCells plugin).
 * @property {string} calculationType String which describes types of calculation which will be performed.
 * @property {string} inlineStartOffset Inline-start offset of the parent container.
 * @property {string} stretchMode Stretch mode 'all' or 'last'.
 * @property {Function} stretchingColumnWidthFn Function that returns the new width of the stretched column.
 */
/**
 * Calculates indexes of columns to render OR columns that are visible.
 * To redo the calculation, you need to create a new calculator.
 *
 * @class ViewportColumnsCalculator
 */
var _totalTargetWidth = /*#__PURE__*/new WeakMap();
var _options = /*#__PURE__*/new WeakMap();
class ViewportColumnsCalculator {
  /**
   * Default column width.
   *
   * @type {number}
   */
  static get DEFAULT_WIDTH() {
    return 50;
  }

  /**
   * Number of rendered/visible columns.
   *
   * @type {number}
   */

  /**
   * @param {ViewportColumnsCalculatorOptions} options Object with all options specified for column viewport calculation.
   */
  constructor(options) {
    _defineProperty(this, "count", 0);
    /**
     * Index of the first rendered/visible column (can be overwritten using overrideFn).
     *
     * @type {number|null}
     */
    _defineProperty(this, "startColumn", null);
    /**
     * Index of the last rendered/visible column (can be overwritten using overrideFn).
     *
     * @type {null}
     */
    _defineProperty(this, "endColumn", null);
    /**
     * Position of the first rendered/visible column (in px).
     *
     * @type {number|null}
     */
    _defineProperty(this, "startPosition", null);
    /**
     * Determines if the viewport is visible in the trimming container.
     *
     * @type {boolean}
     */
    _defineProperty(this, "isVisibleInTrimmingContainer", false);
    /**
     * @type {number}
     */
    _defineProperty(this, "stretchAllRatio", 0);
    /**
     * @type {number}
     */
    _defineProperty(this, "stretchLastWidth", 0);
    /**
     * @type {number}
     */
    _classPrivateFieldInitSpec(this, _totalTargetWidth, {
      writable: true,
      value: 0
    });
    /**
     * @type {boolean}
     */
    _defineProperty(this, "needVerifyLastColumnWidth", true);
    /**
     * @type {number[]}
     */
    _defineProperty(this, "stretchAllColumnsWidth", []);
    /**
     * The calculator options.
     *
     * @type {ViewportColumnsCalculatorOptions}
     */
    _classPrivateFieldInitSpec(this, _options, {
      writable: true,
      value: void 0
    });
    _classPrivateFieldSet(this, _options, options);
    if (typeof _classPrivateFieldGet(this, _options).stretchingColumnWidthFn !== 'function') {
      _classPrivateFieldGet(this, _options).stretchingColumnWidthFn = width => width;
    }
    this.calculate();
  }

  /**
   * Calculates viewport.
   */
  calculate() {
    const {
      calculationType,
      overrideFn,
      scrollOffset,
      totalColumns,
      viewportWidth
    } = _classPrivateFieldGet(this, _options);
    const zeroBasedScrollOffset = Math.max(_classPrivateFieldGet(this, _options).scrollOffset, 0);
    // +1 pixel for row header width compensation for horizontal scroll > 0
    const compensatedViewportWidth = zeroBasedScrollOffset > 0 ? viewportWidth + 1 : viewportWidth;
    let sum = 0;
    let needReverse = true;
    const startPositions = [];
    let columnWidth;
    let firstVisibleColumnWidth = 0;
    let lastVisibleColumnWidth = 0;
    for (let i = 0; i < totalColumns; i++) {
      columnWidth = this._getColumnWidth(i);
      if (sum <= zeroBasedScrollOffset && calculationType !== _constants.FULLY_VISIBLE_TYPE) {
        this.startColumn = i;
        firstVisibleColumnWidth = columnWidth;
      }
      if (sum >= zeroBasedScrollOffset && sum + (calculationType === _constants.FULLY_VISIBLE_TYPE ? columnWidth : 0) <= zeroBasedScrollOffset + compensatedViewportWidth) {
        if (this.startColumn === null || this.startColumn === undefined) {
          this.startColumn = i;
          firstVisibleColumnWidth = columnWidth;
        }
        this.endColumn = i;
      }
      startPositions.push(sum);
      sum += columnWidth;
      lastVisibleColumnWidth = columnWidth;
      if (calculationType !== _constants.FULLY_VISIBLE_TYPE) {
        this.endColumn = i;
      }
      if (sum >= zeroBasedScrollOffset + viewportWidth) {
        needReverse = false;
        break;
      }
    }
    const mostRightScrollOffset = scrollOffset + viewportWidth - compensatedViewportWidth;
    const inlineEndColumnOffset = calculationType === _constants.FULLY_VISIBLE_TYPE ? 0 : lastVisibleColumnWidth;
    const inlineStartColumnOffset = calculationType === _constants.FULLY_VISIBLE_TYPE ? firstVisibleColumnWidth : 0;
    if (
    // the table is to the left of the viewport
    mostRightScrollOffset < -1 * _classPrivateFieldGet(this, _options).inlineStartOffset || scrollOffset > startPositions.at(-1) + inlineEndColumnOffset ||
    // the table is to the right of the viewport
    -1 * _classPrivateFieldGet(this, _options).scrollOffset - _classPrivateFieldGet(this, _options).viewportWidth > -1 * inlineStartColumnOffset) {
      this.isVisibleInTrimmingContainer = false;
    } else {
      this.isVisibleInTrimmingContainer = true;
    }
    if (this.endColumn === totalColumns - 1 && needReverse) {
      this.startColumn = this.endColumn;
      while (this.startColumn > 0) {
        const viewportSum = startPositions[this.endColumn] + columnWidth - startPositions[this.startColumn - 1];
        if (viewportSum <= viewportWidth || calculationType !== _constants.FULLY_VISIBLE_TYPE) {
          this.startColumn -= 1;
        }
        if (viewportSum > viewportWidth) {
          break;
        }
      }
    }
    if (calculationType === _constants.RENDER_TYPE && this.startColumn !== null && overrideFn) {
      overrideFn(this);
    }
    this.startPosition = startPositions[this.startColumn];
    if (this.startPosition === undefined) {
      this.startPosition = null;
    }

    // If totalColumns exceeded its total columns size set endColumn to the latest item
    if (totalColumns < this.endColumn) {
      this.endColumn = totalColumns - 1;
    }
    if (this.startColumn !== null) {
      this.count = this.endColumn - this.startColumn + 1;
    }
  }

  /**
   * Recalculate columns stretching.
   *
   * @param {number} totalWidth The total width of the table.
   */
  refreshStretching(totalWidth) {
    if (_classPrivateFieldGet(this, _options).stretchMode === 'none') {
      return;
    }
    let totalColumnsWidth = totalWidth;
    _classPrivateFieldSet(this, _totalTargetWidth, totalColumnsWidth);
    const totalColumns = _classPrivateFieldGet(this, _options).totalColumns;
    let sumAll = 0;
    for (let i = 0; i < totalColumns; i++) {
      const columnWidth = this._getColumnWidth(i);
      const permanentColumnWidth = _classPrivateFieldGet(this, _options).stretchingColumnWidthFn(undefined, i);
      if (typeof permanentColumnWidth === 'number') {
        totalColumnsWidth -= permanentColumnWidth;
      } else {
        sumAll += columnWidth;
      }
    }
    const remainingSize = totalColumnsWidth - sumAll;
    if (_classPrivateFieldGet(this, _options).stretchMode === 'all' && remainingSize > 0) {
      this.stretchAllRatio = totalColumnsWidth / sumAll;
      this.stretchAllColumnsWidth = [];
      this.needVerifyLastColumnWidth = true;
    } else if (_classPrivateFieldGet(this, _options).stretchMode === 'last' && totalColumnsWidth !== Infinity) {
      const columnWidth = this._getColumnWidth(totalColumns - 1);
      const lastColumnWidth = remainingSize + columnWidth;
      this.stretchLastWidth = lastColumnWidth >= 0 ? lastColumnWidth : columnWidth;
    }
  }

  /**
   * Get stretched column width based on stretchH (all or last) setting passed in handsontable instance.
   *
   * @param {number} column The visual column index.
   * @param {number} baseWidth The default column width.
   * @returns {number|null}
   */
  getStretchedColumnWidth(column, baseWidth) {
    let result = null;
    if (_classPrivateFieldGet(this, _options).stretchMode === 'all' && this.stretchAllRatio !== 0) {
      result = this._getStretchedAllColumnWidth(column, baseWidth);
    } else if (_classPrivateFieldGet(this, _options).stretchMode === 'last' && this.stretchLastWidth !== 0) {
      result = this._getStretchedLastColumnWidth(column);
    }
    return result;
  }

  /**
   * @param {number} column The visual column index.
   * @param {number} baseWidth The default column width.
   * @returns {number}
   * @private
   */
  _getStretchedAllColumnWidth(column, baseWidth) {
    let sumRatioWidth = 0;
    const totalColumns = _classPrivateFieldGet(this, _options).totalColumns;
    if (!this.stretchAllColumnsWidth[column]) {
      const stretchedWidth = Math.round(baseWidth * this.stretchAllRatio);
      const newStretchedWidth = _classPrivateFieldGet(this, _options).stretchingColumnWidthFn(stretchedWidth, column);
      if (newStretchedWidth === undefined) {
        this.stretchAllColumnsWidth[column] = stretchedWidth;
      } else {
        this.stretchAllColumnsWidth[column] = isNaN(newStretchedWidth) ? this._getColumnWidth(column) : newStretchedWidth;
      }
    }
    if (this.stretchAllColumnsWidth.length === totalColumns && this.needVerifyLastColumnWidth) {
      this.needVerifyLastColumnWidth = false;
      for (let i = 0; i < this.stretchAllColumnsWidth.length; i++) {
        sumRatioWidth += this.stretchAllColumnsWidth[i];
      }
      if (sumRatioWidth !== _classPrivateFieldGet(this, _totalTargetWidth)) {
        this.stretchAllColumnsWidth[this.stretchAllColumnsWidth.length - 1] += _classPrivateFieldGet(this, _totalTargetWidth) - sumRatioWidth;
      }
    }
    return this.stretchAllColumnsWidth[column];
  }

  /**
   * @param {number} column The visual column index.
   * @returns {number|null}
   * @private
   */
  _getStretchedLastColumnWidth(column) {
    const totalColumns = _classPrivateFieldGet(this, _options).totalColumns;
    if (column === totalColumns - 1) {
      return this.stretchLastWidth;
    }
    return null;
  }

  /**
   * @param {number} column The visual column index.
   * @returns {number}
   * @private
   */
  _getColumnWidth(column) {
    let width = _classPrivateFieldGet(this, _options).columnWidthFn(column);
    if (isNaN(width)) {
      width = ViewportColumnsCalculator.DEFAULT_WIDTH;
    }
    return width;
  }
}
var _default = ViewportColumnsCalculator;
exports.default = _default;