"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

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

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

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

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

var _constants = require("../../constants");

var _classnames = _interopRequireDefault(require("classnames"));

var _Popper = _interopRequireDefault(require("../Popper"));

var _Menu = _interopRequireWildcard(require("../Menu"));

var _AutoClosable = _interopRequireDefault(require("../AutoClosable"));

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

// Copyright 1999-2020. Plesk International GmbH. All rights reserved.

/* eslint-disable react/prop-types */
const findNextSafeIndex = (currIndex, diff, options) => {
  const maxIndex = options.length - 1;
  let attempt = 0;

  for (let i = currIndex + diff; attempt < options.length; i += diff) {
    attempt += 1;

    if (i > maxIndex) {
      i = 0;
    } else if (i < 0) {
      i = maxIndex;
    }

    if (options[i] && options[i].disabled === false) {
      return i;
    }
  }

  return -1;
};

exports.findNextSafeIndex = findNextSafeIndex;

const ComboBoxDropdown = ({
  baseClassName = "".concat(_constants.CLS_PREFIX, "combobox-dropdown"),
  className,
  control,
  controlRef,
  opened,
  disabled,
  groups,
  options,
  onHighlightedIndexChange,
  onClose,
  value,
  highlightedIndex,
  onSelect,
  noOptions,
  emitter,
  ...props
}) => {
  const rootRef = (0, _react.useRef)(null);
  const menuRef = (0, _react.useRef)(null);
  const [minWidth, setMinWidth] = (0, _react.useState)(0);
  (0, _react.useLayoutEffect)(() => {
    if (opened && rootRef.current) {
      const {
        width
      } = rootRef.current.getBoundingClientRect();

      if (width !== minWidth) {
        setMinWidth(width);
      }
    }
  }, [opened, minWidth]);
  (0, _react.useEffect)(() => {
    if (!opened) {
      return undefined;
    }

    const listener = () => {
      (0, _utils.safeInvoke)(onClose);
    };

    window.addEventListener('resize', listener, {
      once: true
    });
    return () => window.removeEventListener('resize', listener);
  }, [opened, onClose]);
  (0, _react.useEffect)(() => {
    if (!emitter) {
      return;
    }

    emitter.on('focus', index => {
      if (menuRef.current) {
        const target = menuRef.current.querySelector("[data-index=\"".concat(index, "\"]"));

        if (target) {
          (0, _utils.scrollIntoView)(target, {
            behavior: 'instant',
            block: 'nearest',
            boundary: menuRef.current
          });
        }
      }
    });
  }, [emitter]);

  const target = /*#__PURE__*/_react.default.createElement(_AutoClosable.default, {
    onClose: () => {
      setTimeout(() => {
        (0, _utils.safeInvoke)(onClose);
      }, 0);
    },
    ignoreNodes: () => [menuRef.current],
    nodeRef: controlRef
  }, control);

  return /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({
    className: className
  }, props, {
    ref: rootRef
  }), /*#__PURE__*/_react.default.createElement(_Popper.default, {
    target: target,
    targetRef: controlRef,
    show: opened && !disabled,
    className: "".concat(baseClassName, "__popper"),
    zIndex: _constants.Z_INDEX_DROPDOWN
  }, /*#__PURE__*/_react.default.createElement(_Menu.default, {
    style: {
      minWidth
    },
    ref: menuRef,
    className: "".concat(baseClassName, "__menu")
  }, groups.reduce((acc, group) => {
    if (group.label) {
      acc.push( /*#__PURE__*/_react.default.createElement(_Menu.MenuHeader, (0, _extends2.default)({}, group.props, {
        key: "group_".concat(group.label)
      }), group.label));
    }

    group.options.forEach(option => {
      const optionIndex = options.indexOf(option);
      let onClick;
      let onMouseOver;
      let onMouseDown;

      if (!option.disabled) {
        onClick = e => {
          e.preventDefault();
          (0, _utils.safeInvoke)(onSelect, option.value);
        };

        onMouseOver = () => {
          // TODO: use throttle
          (0, _utils.safeInvoke)(onHighlightedIndexChange, optionIndex);
        };

        onMouseDown = e => {
          e.preventDefault();
        };
      }

      const menuItemProps = { ...option.props,
        active: value === option.value,
        className: (0, _classnames.default)("".concat(baseClassName, "__option"), {
          ["".concat(baseClassName, "__option--selected")]: optionIndex === highlightedIndex
        }),
        disabled: option.disabled,
        onClick,
        onMouseOver,
        onMouseDown,
        'data-index': optionIndex
      };
      acc.push( /*#__PURE__*/_react.default.createElement(_Menu.MenuItem, (0, _extends2.default)({
        key: "option_".concat(option.value)
      }, menuItemProps), option.children));
    });
    return acc;
  }, []), options.length === 0 && noOptions && /*#__PURE__*/_react.default.createElement(_Menu.MenuItem, {
    disabled: true,
    className: "".concat(baseClassName, "__no-options")
  }, noOptions))));
};

var _default = ComboBoxDropdown;
exports.default = _default;