/* eslint-disable no-use-before-define */
/* eslint-disable import/prefer-default-export */
// eslint-disable-next-line no-use-before-define
export function setIdleTimeout(seconds, onIdle) {
  let timeout = 0;
  startTimer();

  function startTimer() {
    timeout = setTimeout(onExpires, seconds * 1000);
    document.addEventListener('mousemove', onActivity);
    document.addEventListener('keydown', onActivity);
  }

  function onExpires() {
    timeout = 0;
    onIdle();
  }

  function onActivity() {
    if (timeout) clearTimeout(timeout);
    // since the mouse is moving, we turn off our event hooks for 1 second
    document.removeEventListener('mousemove', onActivity);
    document.removeEventListener('keydown', onActivity);
    setTimeout(startTimer, 1000);
  }
}
