"use strict";

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

var _reduxBundler = require("redux-bundler");

/**
 * @typedef UserInactiveBundleOptions
 * @property {number} [inactiveThreshold=30000] Time in milliseconds after which
 *   to consider the user inactive. Default is `30000`
 * @property {string} [updateActionType='USER_INACTIVE_UPDATED'] Action `type`
 *   to use when updating this. Default is `'USER_INACTIVE_UPDATED'`
 * @property {string} [name='userInactive'] Name of bundle. Default is `'userInactive'`
 * @property {string[]} [events=['mousemove', 'click', 'keydown']] The window
 *   events to listen to. Default is `['mousemove', 'click', 'keydown']`
 */

/**
 * @param {UserInactiveBundleOptions} [opts]
 * @returns {ReduxBundlerBundle}
 */
const getUserInactiveBundle = ({
  inactiveThreshold,
  updateActionType = 'USER_INACTIVE_UPDATED',
  name = 'userInactive',
  events = ['mousemove', 'click', 'keydown']
} = {}) => ({
  name,
  reducer: (state = null, {
    type,
    payload
  }) => type === updateActionType ? payload || null : state,
  selectUserIsActive: state => !state[name],
  selectUserInactiveTime: state => state[name],
  init: store => {
    let lastActiveTime;
    const resetInactivityTimer = (0, _reduxBundler.debounce)(() => {
      store.dispatch({
        type: updateActionType,
        payload: lastActiveTime
      });
    }, inactiveThreshold || 30000);

    const listener = () => {
      lastActiveTime = Date.now();
      resetInactivityTimer();

      if (!store.selectUserIsActive()) {
        store.dispatch({
          type: updateActionType
        });
      }
    };

    events.forEach(eventName => {
      window.addEventListener(eventName, listener, {
        passive: true
      });
    });
    resetInactivityTimer();
  }
});

exports.getUserInactiveBundle = getUserInactiveBundle;