import ElementHelpers from '../helpers/element-helpers';

/**
 * For accessibility purposes the user should be 'trapped' in an overlay/modal by pressing the tab key
 * @param {event, element, modalOpen (needs to be declared in constructor), keystroke (needs to be declared in constructor) }
 */

function trapFocus(event, element, elementIsOpen, keystrokes = 0) {
  const focusableEl = ElementHelpers.getKeyboardFocusableElements(element);
  const firstFocusableEl = focusableEl[0];
  const lastFocusableEl = focusableEl[focusableEl.length - 1];

  if (elementIsOpen) {
    // on the first tab the focus should be on the first focusable element
    if (keystrokes < 1) {
      event.preventDefault();
      setTimeout(function () {
        firstFocusableEl.focus();
      }, 100);
    }
    if (event.shiftKey) {
      if (document.activeElement === firstFocusableEl) {
        event.preventDefault();
        lastFocusableEl.focus();
      }
    } else {
      if (document.activeElement === lastFocusableEl) {
        event.preventDefault();
        firstFocusableEl.focus();
      }
    }
  }
}

export default trapFocus;
