import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import { useCallback, useRef } from 'react';
import Events from '../utils/events';
import { useLatest } from '../utils/hooks';

var isTouchEvent = function isTouchEvent(ev) {
  return 'touches' in ev;
};

var preventDefault = function preventDefault(ev) {
  if (!isTouchEvent(ev)) return;

  if (ev.touches.length < 2 && ev.preventDefault) {
    ev.preventDefault();
  }
};

var useLongPress = function useLongPress(_ref) {
  var _ref$isPreventDefault = _ref.isPreventDefault,
      isPreventDefault = _ref$isPreventDefault === void 0 ? true : _ref$isPreventDefault,
      _ref$delay = _ref.delay,
      delay = _ref$delay === void 0 ? 300 : _ref$delay,
      restProps = _objectWithoutProperties(_ref, ["isPreventDefault", "delay"]);

  var onLongPress = restProps.onLongPress,
      onPress = restProps.onPress,
      onClear = restProps.onClear;
  var timeout = useRef(0);
  var target = useRef();
  var onLongPressRef = useLatest(onLongPress);
  var onPressRef = useLatest(onPress);
  var onClearRef = useLatest(onClear);
  var startedRef = useRef(false);
  var start = useCallback(function (event) {
    // prevent ghost click on mobile devices
    if (isPreventDefault && event.target instanceof Element) {
      Events.on(event.target, 'touchend', preventDefault, {
        passive: false
      });
      target.current = event.target;
    }

    if (typeof onPressRef.current === 'function') {
      onPressRef.current(event);
    }

    if (typeof onLongPressRef.current === 'function') {
      timeout.current = window.setTimeout(function () {
        onLongPressRef.current(event);
      }, delay);
    }

    startedRef.current = true;
  }, [delay, isPreventDefault]);
  var clear = useCallback(function (event) {
    if (!startedRef.current) {
      return;
    } // clearTimeout and removeEventListener


    if (timeout.current) {
      window.clearTimeout(timeout.current);
    }

    if (typeof onClearRef.current === 'function') {
      onClearRef.current(event);
    }

    if (isPreventDefault && target.current instanceof Element) {
      Events.off(target.current, 'touchend', preventDefault);
    }
  }, [isPreventDefault]);
  return {
    onTouchStart: start,
    onTouchEnd: clear,
    onMouseDown: start,
    onMouseUp: clear,
    onMouseLeave: clear
  };
};

export default useLongPress;