'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var React = require('react');

function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }

function _interopNamespaceCompat(e) {
    if (e && typeof e === 'object' && 'default' in e) return e;
    var n = Object.create(null);
    if (e) {
        Object.keys(e).forEach(function (k) {
            if (k !== 'default') {
                var d = Object.getOwnPropertyDescriptor(e, k);
                Object.defineProperty(n, k, d.get ? d : {
                    enumerable: true,
                    get: function () { return e[k]; }
                });
            }
        });
    }
    n.default = e;
    return Object.freeze(n);
}

var _slicedToArray__default = /*#__PURE__*/_interopDefaultCompat(_slicedToArray);
var React__namespace = /*#__PURE__*/_interopNamespaceCompat(React);

/**
 * Reack hook
 */
var useKeyPress = function useKeyPress(targetKey, handleKeyDown, handleKeyUp) {
  // State for keeping track of whether key is pressed
  var _React$useState = React__namespace.useState(false),
    _React$useState2 = _slicedToArray__default.default(_React$useState, 2),
    keyPressed = _React$useState2[0],
    setKeyPressed = _React$useState2[1];

  // If pressed key is our target key then set to true
  var downHandler = function downHandler(event) {
    if (event.key === targetKey) {
      if (handleKeyDown) {
        handleKeyDown(event);
      } else {
        setKeyPressed(true);
      }
    }
  };

  // If released key is our target key then set to false
  var upHandler = function upHandler(event) {
    if (event.key === targetKey) {
      if (handleKeyUp) {
        handleKeyUp(event);
      } else {
        setKeyPressed(false);
      }
    }
  };

  // Add event listeners
  React__namespace.useEffect(function () {
    window.addEventListener('keydown', downHandler);
    window.addEventListener('keyup', upHandler);
    // Remove event listeners on cleanup
    return function () {
      window.removeEventListener('keydown', downHandler);
      window.removeEventListener('keyup', upHandler);
    };
  }, [targetKey, handleKeyDown, handleKeyUp]);
  return keyPressed;
};

exports.useKeyPress = useKeyPress;
