import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import { useCallback, useEffect, useReducer, useRef } from 'react';
import { useGlobalListener } from '@restart/hooks';
import { keyMirror } from 'ramda-extension';
var EVENTS = Object.freeze(['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart']);
var initialState = {
  isIdle: false,
  idleStart: null
};
var ActionTypes = keyMirror({
  RESET: null,
  START: null
});

var reducer = function reducer(state, action) {
  switch (action.type) {
    case ActionTypes.RESET:
      {
        return initialState;
      }

    case ActionTypes.START:
      {
        return {
          isIdle: true,
          startIdleTime: action.payload.time
        };
      }

    default:
      {
        return state;
      }
  }
};
/**
 * Detects if user is active.  It checks for mouse movements in the window. If
 * there is no event fired in `idleTimeout` interval, than is we consider
 * window in `idle` state.
 *
 * @param {number} idleTimeout
 *
 * @return {Object} API
 * @return {boolean} API.isIdle True, if user is considered inactive.
 * @return {number} API.startIdleTime number Timestamp - when we swithed to
 * `isIdle === true`
 */


export var useIdleTime = function useIdleTime() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$idleTimeout = _ref.idleTimeout,
      idleTimeout = _ref$idleTimeout === void 0 ? 5000 : _ref$idleTimeout;

  var timer = useRef();

  var _useReducer = useReducer(reducer, initialState),
      _useReducer2 = _slicedToArray(_useReducer, 2),
      state = _useReducer2[0],
      dispatch = _useReducer2[1];

  var resetTimer = useCallback(function () {
    dispatch({
      type: ActionTypes.RESET
    });
    clearTimeout(timer.current);
    timer.current = setTimeout(function () {
      return void dispatch({
        type: ActionTypes.START,
        payload: {
          time: Date.now()
        }
      });
    }, idleTimeout);
  }, [dispatch, idleTimeout]);
  useEffect(function () {
    return void resetTimer();
  }, [resetTimer]);
  EVENTS.forEach(function (name) {
    // NOTE: `EVENTS` is constant array that is not meant for mutation.
    // The order of calling the `useGlobalListener` hook should be always
    // the same.
    // eslint-disable-next-line react-hooks/rules-of-hooks
    useGlobalListener(name, resetTimer, true);
  });
  return state;
};
export default useIdleTime;