import { useEffect, useCallback } from 'react';
import helper from '../DOMHelper';
import { getDOMNode, KEY_CODE } from './';

function isLeftClickEvent(event) {
  return (event === null || event === void 0 ? void 0 : event.button) === 0;
}

function isModifiedEvent(event) {
  return !!(event.metaKey || event.altKey || event.ctrlKey || (event === null || event === void 0 ? void 0 : event.shiftKey));
}

/**
 * A hook that listens to the document click event and closes the overlay.
 * @param onRootClose
 * @param param1
 */
function useRootClose(onRootClose, _ref) {
  var disabled = _ref.disabled,
      triggerTarget = _ref.triggerTarget,
      overlayTarget = _ref.overlayTarget;
  var handleDocumentKeyUp = useCallback(function (event) {
    if (event.keyCode === KEY_CODE.ESC) {
      onRootClose === null || onRootClose === void 0 ? void 0 : onRootClose(event);
    }
  }, [onRootClose]);
  var handleDocumentClick = useCallback(function (event) {
    var triggerElement = getDOMNode(triggerTarget);
    var overlayElement = getDOMNode(overlayTarget); // Check if the clicked element is a trigger.

    if (triggerElement && helper.contains(triggerElement, event.target)) {
      return;
    } // Check if the clicked element is a overlay.


    if (overlayElement && helper.contains(overlayElement, event.target)) {
      return;
    }

    if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
      return;
    }

    onRootClose === null || onRootClose === void 0 ? void 0 : onRootClose(event);
  }, [onRootClose, triggerTarget, overlayTarget]);
  useEffect(function () {
    var currentTarget = getDOMNode(triggerTarget);
    if (disabled || !currentTarget) return;
    var doc = helper.ownerDocument(currentTarget);
    var onDocumentClickListener = helper.on(doc, 'click', handleDocumentClick, true);
    var onDocumentKeyupListener = helper.on(doc, 'keyup', handleDocumentKeyUp);
    return function () {
      onDocumentClickListener === null || onDocumentClickListener === void 0 ? void 0 : onDocumentClickListener.off();
      onDocumentKeyupListener === null || onDocumentKeyupListener === void 0 ? void 0 : onDocumentKeyupListener.off();
    };
  }, [triggerTarget, disabled, onRootClose, handleDocumentClick, handleDocumentKeyUp]);
}

export default useRootClose;