"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireDefault(require("react"));

var _guid = _interopRequireDefault(require("../../util/guid"));

var _reactDom = require("react-dom");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var groupBy = function groupBy(array, field) {
  var id;
  var result = Object.create(null);

  if (typeof field === 'string') {
    var _iteratorNormalCompletion = true;
    var _didIteratorError = false;
    var _iteratorError = undefined;

    try {
      for (var _iterator = array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
        var item = _step.value;
        id = String(item[field]);

        if (!result[id]) {
          result[id] = [item];
        } else {
          result[id].push(item);
        }
      }
    } catch (err) {
      _didIteratorError = true;
      _iteratorError = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion && _iterator["return"] != null) {
          _iterator["return"]();
        }
      } finally {
        if (_didIteratorError) {
          throw _iteratorError;
        }
      }
    }
  } else if (typeof field === 'function') {
    var _iteratorNormalCompletion2 = true;
    var _didIteratorError2 = false;
    var _iteratorError2 = undefined;

    try {
      for (var _iterator2 = array[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
        var _item = _step2.value;
        id = String(field(_item));

        if (!result[id]) {
          result[id] = [_item];
        } else {
          result[id].push(_item);
        }
      }
    } catch (err) {
      _didIteratorError2 = true;
      _iteratorError2 = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
          _iterator2["return"]();
        }
      } finally {
        if (_didIteratorError2) {
          throw _iteratorError2;
        }
      }
    }
  }

  return result;
};

var getBestWidth = function getBestWidth(_ref) {
  var headerWidth = _ref.headerWidth,
      bodyWidths = _ref.bodyWidths;
  var sizeGroup = groupBy(bodyWidths, function (size) {
    var groupIndex = (size / 10).toFixed();
    return groupIndex;
  });
  var values = Object.values(sizeGroup).sort(function (sizesA, sizesB) {
    return sizesB.length - sizesA.length;
  })[0]; // const value = values.reduce( ( pv, cv, i ) => ( ( pv * i + cv ) / ( i + 1 ) ), 0 );

  var value = Math.max.apply(null, values);
  return Math.max(headerWidth, value);
};

var AutoWidth =
/*#__PURE__*/
function () {
  function AutoWidth() {
    var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref2$padding = _ref2.padding,
        padding = _ref2$padding === void 0 ? null : _ref2$padding,
        table = _ref2.table;

    _classCallCheck(this, AutoWidth);

    _defineProperty(this, "padding", 15);

    _defineProperty(this, "enable", true);

    _defineProperty(this, "columns", Object.create(null));

    _defineProperty(this, "Calculators", Object.create(null));

    _defineProperty(this, "colGroups", []);

    if (typeof padding === 'number') {
      this.padding = padding;
    }

    this.table = table;
  }

  _createClass(AutoWidth, [{
    key: "init",
    value: function init() {
      this.columns = Object.create(null);
      this.Calculators = Object.create(null);
      this.colGroups.length = 0;
    }
  }, {
    key: "analyzeColDefine",
    value: function analyzeColDefine(column) {
      if (column && column.width === 'auto') {
        this.columns[column.columnId] = {
          calced: false,
          headerCalculator: null,
          headerWidth: null,
          bodyCalculators: [],
          bodyWidths: [],
          bestWidth: null,
          isMax: false
        };
      }
    }
  }, {
    key: "bindColGroup",
    value: function bindColGroup(colGroup) {
      if (!this.enable) {
        return;
      }

      var colGroups = this.colGroups;

      if (!colGroups.includes(colGroup)) {
        colGroups.push(colGroup);
      }
    }
  }, {
    key: "bindCalculator",
    value: function bindCalculator(id, target) {
      this.Calculators[id] = target;
    }
  }, {
    key: "renderCalculator",
    value: function renderCalculator(columnId, isInHeader, content, children) {
      if (!this.enable) {
        return null;
      }

      var column = this.columns[columnId];

      if (column) {
        var calculatorId = (0, _guid["default"])('aw-');

        if (isInHeader) {
          column.headerCalculator = calculatorId;
        } else {
          column.bodyCalculators.push(calculatorId);
        }

        return _react["default"].createElement(Calculator, {
          id: calculatorId,
          AutoWidthInstance: this
        }, content, children);
      } else {
        return null;
      }
    }
  }, {
    key: "calcAndUpdate",
    value: function calcAndUpdate() {
      var _this = this;

      var colGroups = this.colGroups,
          columns = this.columns;
      var columnIds = Object.keys(columns);
      var maxValue = 0;
      var maxValueId = null;

      for (var _i = 0, _columnIds = columnIds; _i < _columnIds.length; _i++) {
        var id = _columnIds[_i];
        var _column = columns[id];
        var headerCalculator = _column.headerCalculator,
            bodyCalculators = _column.bodyCalculators;

        if (headerCalculator) {
          _column.headerWidth = this.Calculators[headerCalculator].getWidth();
        }

        if (bodyCalculators.length) {
          _column.bodyWidths = bodyCalculators.map(function (i) {
            return _this.Calculators[i].getWidth();
          });
        }

        if (_column.bodyWidths.length) {
          _column.bestWidth = getBestWidth(_column);

          if (_column.bestWidth > maxValue) {
            maxValue = _column.bestWidth;
            maxValueId = id;
          }
        }
      }

      if (maxValueId) {
        var column = columns[maxValueId];
        column.bestWidth = null;
      }

      var _iteratorNormalCompletion3 = true;
      var _didIteratorError3 = false;
      var _iteratorError3 = undefined;

      try {
        for (var _iterator3 = colGroups[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
          var colGroup = _step3.value;
          colGroup.forceUpdate();
        }
      } catch (err) {
        _didIteratorError3 = true;
        _iteratorError3 = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) {
            _iterator3["return"]();
          }
        } finally {
          if (_didIteratorError3) {
            throw _iteratorError3;
          }
        }
      }
    }
  }, {
    key: "getBestWidth",
    value: function getBestWidth(columnId) {
      var column = this.columns[columnId];

      if (column && column.bestWidth) {
        return column.bestWidth + this.padding * 2;
      } else {
        return null;
      }
    }
  }]);

  return AutoWidth;
}();

exports["default"] = AutoWidth;

var Calculator =
/*#__PURE__*/
function (_React$Component) {
  _inherits(Calculator, _React$Component);

  function Calculator(props) {
    var _this2;

    _classCallCheck(this, Calculator);

    _this2 = _possibleConstructorReturn(this, _getPrototypeOf(Calculator).call(this, props));
    var _this2$props = _this2.props,
        AutoWidthInstance = _this2$props.AutoWidthInstance,
        id = _this2$props.id;
    AutoWidthInstance.bindCalculator(id, _assertThisInitialized(_this2));
    return _this2;
  }

  _createClass(Calculator, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      var _this$props = this.props,
          AutoWidthInstance = _this$props.AutoWidthInstance,
          id = _this$props.id;
      AutoWidthInstance.bindCalculator(id, this);
      var container = (0, _reactDom.findDOMNode)(this);
      container.style.display = 'block';
    }
  }, {
    key: "getWidth",
    value: function getWidth() {
      var container = (0, _reactDom.findDOMNode)(this);
      var content = container.querySelector('.auto-width-calculator-content');

      var _content$getBoundingC = content.getBoundingClientRect(),
          width = _content$getBoundingC.width;

      container.style.display = 'none';
      return width;
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props2 = this.props,
          content = _this$props2.content,
          children = _this$props2.children;
      return _react["default"].createElement("div", {
        style: {
          cssText: 'position: relative; opacity: 0; pointer-events: none'
        }
      }, _react["default"].createElement("div", {
        style: {
          cssText: 'position: absolute; width: 2000px'
        }
      }, _react["default"].createElement("div", {
        className: "auto-width-calculator-content",
        style: {
          cssText: 'position: absolute'
        }
      }, content, children)));
    }
  }]);

  return Calculator;
}(_react["default"].Component);