import {TBlock, TDocument, TPhrasing} from 'react-native-render-html';

type ImageParentNode = TBlock | TDocument | TPhrasing | null;

/**
 * This value is to avoid traversing the entire HTML tree.
 */
const MAX_RECURSIVITY = 5;

/**
 * Helper to get the closest "a" node
 */
export const getParentLink = (
  tnode?: ImageParentNode,
  loopNumber = 0,
): ImageParentNode => {
  if (!tnode?.parent || loopNumber > MAX_RECURSIVITY) {
    return null;
  }

  return tnode.parent.tagName === 'a'
    ? tnode.parent
    : getParentLink(tnode.parent, loopNumber + 1);
};
