import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import 'core-js/modules/es.array.find-index.js';
import React__default, { useState, useImperativeHandle } from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import { settings } from '../../../constants/Settings.js';
import { MIN_COLUMN_WIDTH } from './columnWidthUtilityFunctions.js';

var propTypes = {
  currentColumnWidths: PropTypes.objectOf(PropTypes.shape({
    width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    id: PropTypes.string
  })).isRequired,
  columnId: PropTypes.string.isRequired,
  onResize: PropTypes.func.isRequired,
  ordering: PropTypes.arrayOf(PropTypes.object).isRequired,
  paddingExtra: PropTypes.number.isRequired,
  preserveColumnWidths: PropTypes.bool.isRequired,
  showExpanderColumn: PropTypes.bool.isRequired
};
var dragHandleWidth = 4;
var iotPrefix = settings.iotPrefix;
var getColumnDragBounds = function getColumnDragBounds(_ref) {
  var myColumn = _ref.myColumn,
    affectedSiblingColumn = _ref.affectedSiblingColumn,
    paddingExtra = _ref.paddingExtra,
    preserveColumnWidths = _ref.preserveColumnWidths;
  var minWidth = 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.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 = useState(0),
    _useState2 = _slicedToArray(_useState, 2),
    startX = _useState2[0],
    setStartX = _useState2[1];
  var _useState3 = useState(0),
    _useState4 = _slicedToArray(_useState3, 2),
    leftPosition = _useState4[0],
    setLeftPosition = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    columnIsBeingResized = _useState6[0],
    setColumnIsBeingResized = _useState6[1];
  var _useState7 = useState(),
    _useState8 = _slicedToArray(_useState7, 2),
    myColumn = _useState8[0],
    setMyColumn = _useState8[1];
  var _useState9 = useState(),
    _useState10 = _slicedToArray(_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 = 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.
  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.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("".concat(iotPrefix, "--column-resize-handle"), _defineProperty({}, "".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;

export { ColumnResize$1 as default, getColumnDragBounds, getUpdatedColumnWidths };
