import { keyCodes } from './keyCodes'

const getFirstEle= (node)=>{
  let first = node.parentNode.firstChild;
  while(first) {
    if (first.nodeType === Node.ELEMENT_NODE) {
      if (first.getAttribute("data-aria-listitem") === 'true') return first;
    }
    first = first.nextSibling;
  }
  return null;
}

const getLastEle= (node)=>{
  let last = node.parentNode.lastChild;
  while(last) {
    if (last.nodeType === Node.ELEMENT_NODE) {
      if (last.getAttribute("data-aria-listitem") === 'true') return last;
    }
    last = last.previousSibling;
  }
  return last;
}

const getNextEle = (node)=>{
  let next = node.nextSibling;
  while(next) {
    if (next.nodeType === Node.ELEMENT_NODE) {
      if (next.getAttribute("data-aria-listitem") === 'true') return next;
    }
    next = next.nextSibling;
  }
  return null;
}

const getPreviousEle = (node)=>{
  let prev = node.previousSibling;
  while(prev) {
    if (prev.nodeType === Node.ELEMENT_NODE) {
      if (prev.getAttribute("data-aria-listitem") === 'true') return prev;
    }
    prev = prev.previousSibling;
  }
  return null;
}

const setFocus = (node)=>{
  let getCompType = node && node.getAttribute('role');
  if(getCompType === 'radio'){
    node['click'] && node.click()
  }
  node && node.setAttribute('tabIndex','0');
  node && node.focus();
  // node && node.scrollIntoView()
}

const arrowNavigate = (event,currentActiveEle)=>{
  let { leftArrow,rightArrow,topArrow,bottomArrow } = keyCodes;
  if(currentActiveEle.dataset.ariaNavigation){
    let arrowPermission = (currentActiveEle.dataset.ariaNavigation || '').split(',');
    
    arrowPermission.forEach((item, i) => {
      let [ keyName ] = (item || '').split('-');
      let nextEle;
      if(keyName && (parseInt(keyName) === leftArrow || parseInt(keyName) === topArrow) && parseInt(keyName) === event.keyCode){
        if(parseInt(keyName) === topArrow){ event && event.preventDefault() }
        nextEle = getPreviousEle(currentActiveEle);
        if(!nextEle){
          nextEle = getLastEle(currentActiveEle)
        }
      }
      if(keyName && (parseInt(keyName) === rightArrow || parseInt(keyName) === bottomArrow) && parseInt(keyName) === event.keyCode){
        if(parseInt(keyName) === bottomArrow){ event && event.preventDefault() }
        nextEle = getNextEle(currentActiveEle);
        if(!nextEle){
          nextEle = getFirstEle(currentActiveEle)
        }
      }
      if(nextEle){
        setFocus(nextEle);
      }
    })
  }
}

export default arrowNavigate;

