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];

  // Tab helpers for iframes.
  // If iframe is the last focusable element, an extra div is being placed so trapfocus is in place.
  // Since it can't detect elements in the iframe itself

  if (!elementIsOpen) {
    return;
  }

  if (lastFocusableEl.tagName && lastFocusableEl.tagName === 'IFRAME') {
    const iframeTabHelper = document.createElement('div');
    iframeTabHelper.setAttribute('tabindex', '0');
    lastFocusableEl.parentNode.insertBefore(
      iframeTabHelper,
      lastFocusableEl.nextSibling
    );
  }

  if (firstFocusableEl.tagName && firstFocusableEl.tagName === 'IFRAME') {
    const iframeTabHelper = document.createElement('div');
    iframeTabHelper.setAttribute('tabindex', '0');
    lastFocusableEl.parentNode.insertBefore(
      iframeTabHelper,
      lastFocusableEl.nextSibling
    );

    firstFocusableEl.parentNode.insertBefore(iframeTabHelper, firstFocusableEl);
  }
  // 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;
