'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
require('core-js/modules/es.array.find-index.js');
var React = require('react');
var classnames = require('classnames');
var PropTypes = require('prop-types');
var Settings = require('../../../constants/Settings.js');
var columnWidthUtilityFunctions = require('./columnWidthUtilityFunctions.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var React__default = /*#__PURE__*/_interopDefault(React);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);

var propTypes = {
  currentColumnWidths: PropTypes__default.default.objectOf(PropTypes__default.default.shape({
    width: PropTypes__default.default.oneOfType([PropTypes__default.default.number, PropTypes__default.default.string]),
    id: PropTypes__default.default.string
  })).isRequired,
  columnId: PropTypes__default.default.string.isRequired,
  onResize: PropTypes__default.default.func.isRequired,
  ordering: PropTypes__default.default.arrayOf(PropTypes__default.default.object).isRequired,
  paddingExtra: PropTypes__default.default.number.isRequired,
  preserveColumnWidths: PropTypes__default.default.bool.isRequired,
  showExpanderColumn: PropTypes__default.default.bool.isRequired
};
var dragHandleWidth = 4;
var iotPrefix = Settings.settings.iotPrefix;
var getColumnDragBounds = function getColumnDragBounds(_ref) {
  var myColumn = _ref.myColumn,
    affectedSiblingColumn = _ref.affectedSiblingColumn,
    paddingExtra = _ref.paddingExtra,
    preserveColumnWidths = _ref.preserveColumnWidths;
  var minWidth = columnWidthUtilityFunctions.MIN_COLUMN_WIDTH + paddingExtra;
  return {
    minWidth: minWidth,
    left: document.dir === 'rtl' ? preserveColumnWidths ? -Infinity : minWidth - affectedSiblingColumn.width : minWidth,
    right: document.dir === 'rtl' ? myColumn.width - minWidth : preserveColumnWidths ? Infinity : myColumn.width + affectedSiblingColumn.width - minWidth
  };
};
var getUpdatedColumnWidths = function getUpdatedColumnWidths(_ref2) {
  var dropXPos = _ref2.dropXPos,
    myColumn = _ref2.myColumn,
    affectedSiblingColumn = _ref2.affectedSiblingColumn,
    preserveColumnWidths = _ref2.preserveColumnWidths;
  var myColumnNewWidth = document.dir === 'rtl' ? myColumn.width - dropXPos : dropXPos;
  var updatedColumns = [{
    id: myColumn.id,
    width: myColumnNewWidth
  }];
  if (!affectedSiblingColumn.isExpanderColumn && !preserveColumnWidths) {
    var newAffectedSiblingColumnWidth = document.dir === 'rtl' ? affectedSiblingColumn.width + dropXPos : affectedSiblingColumn.width + myColumn.width - dropXPos;
    updatedColumns.push({
      id: affectedSiblingColumn.id,
      width: newAffectedSiblingColumnWidth
    });
  }
  return updatedColumns;
};
var findNextVisibleSibling = function findNextVisibleSibling(_ref3) {
  var _ordering$nextColInde;
  var ordering = _ref3.ordering,
    myColIndex = _ref3.myColIndex,
    currentColumnWidths = _ref3.currentColumnWidths,
    showExpanderColumn = _ref3.showExpanderColumn;
  var nextColIndex = ordering.findIndex(function (col, i) {
    return i > myColIndex && !col.isHidden;
  });
  var nextColId = (_ordering$nextColInde = ordering[nextColIndex]) === null || _ordering$nextColInde === void 0 ? void 0 : _ordering$nextColInde.columnId;
  return nextColIndex === -1 && showExpanderColumn ? {
    width: Infinity,
    isExpanderColumn: true
  } : currentColumnWidths[nextColId];
};
var ColumnResize = /*#__PURE__*/React__default.default.forwardRef(function (props, ref) {
  var currentColumnWidths = props.currentColumnWidths,
    columnId = props.columnId,
    ordering = props.ordering,
    paddingExtra = props.paddingExtra,
    showExpanderColumn = props.showExpanderColumn,
    preserveColumnWidths = props.preserveColumnWidths;
  var _useState = React.useState(0),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    startX = _useState2[0],
    setStartX = _useState2[1];
  var _useState3 = React.useState(0),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    leftPosition = _useState4[0],
    setLeftPosition = _useState4[1];
  var _useState5 = React.useState(false),
    _useState6 = _slicedToArray__default.default(_useState5, 2),
    columnIsBeingResized = _useState6[0],
    setColumnIsBeingResized = _useState6[1];
  var _useState7 = React.useState(),
    _useState8 = _slicedToArray__default.default(_useState7, 2),
    myColumn = _useState8[0],
    setMyColumn = _useState8[1];
  var _useState9 = React.useState(),
    _useState10 = _slicedToArray__default.default(_useState9, 2),
    affectedSiblingColumn = _useState10[0],
    setAffectedSiblingColumn = _useState10[1];
  var setAffectedColumns = function setAffectedColumns() {
    var myCol = currentColumnWidths[columnId];
    setMyColumn(myCol);
    var myColIndex = ordering.findIndex(function (col) {
      return col.columnId === columnId;
    });
    var siblingColumn = findNextVisibleSibling({
      ordering: ordering,
      myColIndex: myColIndex,
      currentColumnWidths: currentColumnWidths,
      showExpanderColumn: showExpanderColumn
    });
    setAffectedSiblingColumn(siblingColumn);
  };
  var handleKeyDown = function handleKeyDown(e) {
    var myCol = currentColumnWidths[columnId];
    var currentWidth = parseInt(myCol.width, 10) || 0;
    var increment = 20;
    var minWidth = columnWidthUtilityFunctions.MIN_COLUMN_WIDTH + paddingExtra;
    if (e.key === 'ArrowRight') {
      var newWidth = currentWidth + increment;
      props.onResize([{
        id: columnId,
        width: newWidth
      }]);
    }
    if (e.key === 'ArrowLeft') {
      var _newWidth = Math.max(minWidth, currentWidth - increment);
      props.onResize([{
        id: columnId,
        width: _newWidth
      }]);
    }
  };
  var _onMouseDown = function onMouseDown(e) {
    e.currentTarget.focus();
    var startingX = e.target.offsetLeft - e.clientX;
    setStartX(startingX);
    setLeftPosition(e.target.offsetLeft);
    setColumnIsBeingResized(true);
    setAffectedColumns();
  };
  var onMouseMove = function onMouseMove(e) {
    if (columnIsBeingResized) {
      var mousePosition = e.clientX + startX;
      getColumnDragBounds({
        myColumn: myColumn,
        affectedSiblingColumn: affectedSiblingColumn,
        paddingExtra: paddingExtra,
        preserveColumnWidths: preserveColumnWidths
      });
      // if (mousePosition > bounds.left && mousePosition < bounds.right) {
      setLeftPosition(mousePosition);
      // }
    }
  };
  var onMouseUp = function onMouseUp() {
    if (columnIsBeingResized) {
      var dropXPos = leftPosition + (document.dir === 'rtl' ? 0 : dragHandleWidth);
      var colWidths = getUpdatedColumnWidths({
        dropXPos: dropXPos,
        myColumn: myColumn,
        affectedSiblingColumn: affectedSiblingColumn,
        preserveColumnWidths: preserveColumnWidths
      });
      props.onResize(colWidths);
      setColumnIsBeingResized(false);
      setLeftPosition(0);
    }
  };

  // We extend this instance with mouse move/up event forward functions which the parent
  // component must call using forward referencing. We do this since the mouse move/up
  // logic belongs to this component, but the events have to be captured by the parent
  // component (with the larger HTML element surface). An alternative to this solution
  // would have been to pass down the mouse coordinates via props, but that resulted in
  // a sluggish rendering since the parent component would have to render for all events
  // during the mouse move.
  React.useImperativeHandle(ref, function () {
    return {
      forwardMouseEvent: function forwardMouseEvent(e) {
        if (e.nativeEvent.type === 'mousemove') {
          onMouseMove(e);
          /* istanbul ignore else */
        } else if (e.nativeEvent.type === 'mouseup') {
          onMouseUp();
        }
      }
    };
  });
  return (
    /*#__PURE__*/
    // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
    React__default.default.createElement("div", {
      role: "button",
      tabIndex: 0,
      onKeyDown: handleKeyDown,
      onClick: function onClick(e) {
        return e.stopPropagation();
      },
      onMouseDown: function onMouseDown(e) {
        return _onMouseDown(e);
      },
      style: {
        width: dragHandleWidth,
        left: leftPosition || (document.dir === 'rtl' ? 0 : 'auto')
      },
      className: classnames__default.default("".concat(iotPrefix, "--column-resize-handle"), _defineProperty__default.default({}, "".concat(iotPrefix, "--column-resize-handle--dragging"), columnIsBeingResized))
    })
  );
});
ColumnResize.propTypes = propTypes;
ColumnResize.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "ColumnResize",
  "props": {
    "currentColumnWidths": {
      "description": "",
      "type": {
        "name": "objectOf",
        "value": {
          "name": "shape",
          "value": {
            "width": {
              "name": "union",
              "value": [{
                "name": "number"
              }, {
                "name": "string"
              }],
              "required": false
            },
            "id": {
              "name": "string",
              "required": false
            }
          }
        }
      },
      "required": true
    },
    "columnId": {
      "description": "",
      "type": {
        "name": "string"
      },
      "required": true
    },
    "onResize": {
      "description": "",
      "type": {
        "name": "func"
      },
      "required": true
    },
    "ordering": {
      "description": "",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "object"
        }
      },
      "required": true
    },
    "paddingExtra": {
      "description": "",
      "type": {
        "name": "number"
      },
      "required": true
    },
    "preserveColumnWidths": {
      "description": "",
      "type": {
        "name": "bool"
      },
      "required": true
    },
    "showExpanderColumn": {
      "description": "",
      "type": {
        "name": "bool"
      },
      "required": true
    }
  }
};
var ColumnResize$1 = ColumnResize;

exports.default = ColumnResize$1;
exports.getColumnDragBounds = getColumnDragBounds;
exports.getUpdatedColumnWidths = getUpdatedColumnWidths;
