import { filterByFocusable } from 'grommet/es6/utils';


export var focusableChildren = function focusableChildren(parent) {
  var list = [];
  if (parent && parent.childNodes) {
    parent.childNodes.forEach(function (node) {
      if (node.tagName) {
        list.push(node);
        if (filterByFocusable([node]).length !== 1) {
          list = list.concat(focusableChildren(node));
        }
      }
    });
  }
  return filterByFocusable(list);
};

export var focusedChildIndex = function focusedChildIndex(parent) {
  var focusable = focusableChildren(parent);
  var focused = document.activeElement;
  for (var i = 0; i < focusable.length; i += 1) {
    if (focusable[i] === focused) {
      return i;
    }
  }
  return 0;
};

export var focusChildByIndex = function focusChildByIndex(parent, index) {
  var focusable = focusableChildren(parent);
  var focusIndex = Math.min(index, focusable.length - 1);
  if (focusIndex >= 0) {
    focusable[focusIndex].focus();
    return true;
  }
  return false;
};

export var focusNextElement = function focusNextElement(parent) {
  var focusable = focusableChildren(parent);
  var focused = document.activeElement;
  var nextFocus = void 0;
  for (var i = 0; i < focusable.length; i += 1) {
    if (focusable[i] === focused) {
      if (i < focusable.length - 1) {
        nextFocus = focusable[i + 1];
      }
      break;
    }
  }
  if (nextFocus) {
    nextFocus.focus();
    return true;
  }
  return false;
};

export var focusPrevElement = function focusPrevElement(parent) {
  var focusable = focusableChildren(parent);
  var focused = document.activeElement;
  var prevFocus = void 0;
  for (var i = 0; i < focusable.length; i += 1) {
    if (focusable[i] === focused) {
      if (i > 0) {
        prevFocus = focusable[i - 1];
      }
      break;
    }
  }
  if (prevFocus) {
    prevFocus.focus();
    return true;
  }
  return false;
};

export var hasKeyboardChildren = function hasKeyboardChildren(element) {
  var currentTag = element.tagName.toLowerCase();
  var validTags = /(input|select|textarea)$/;
  if (currentTag.match(validTags)) {
    return true;
  }
  var focusable = focusableChildren(element);
  for (var i = 0; i < focusable.length; i += 1) {
    if (focusable[i].tagName && focusable[i].tagName.toLowerCase().match(validTags)) {
      return true;
    }
  }
  return false;
};