const spaceRegex = /\s+/g;
const endDotRegex = /\.$/;
const doubleDotRegex = /\.+/g;

type GetFriendlySelectorFn = (element: HTMLElement) => string;
export const getFriendlySelector: GetFriendlySelectorFn = (element) => {
  if (element.tagName.toLowerCase() == 'body') return 'body';
  let str = element.tagName.toLowerCase();

  if (element.className && element.className.split) {
    let classes = element.className.split(spaceRegex);
    for (let i = 0; i < classes.length; i++) {
      if (typeof classes[i] === 'string') {
        const theClass = classes[i];
        if (!theClass) continue;
        if (theClass.trim().length > 0) {
          if (theClass.indexOf(':') === -1 && theClass.indexOf('[') === -1) {
            str += '.' + theClass;
          }
        }
      }
    }
    str = str.replace(endDotRegex, '').replace(doubleDotRegex, '.');
  }

  const id = element.getAttribute('id');
  str += !!id && id.indexOf('=') < 0 ? '#' + id : '';

  return getFriendlySelector(element.parentNode as HTMLElement) + ' > ' + str;
};

type GetSelectorFn = (element: HTMLElement) => string;
export const getSelector: GetSelectorFn = (element) => {
  if (!element || element === document.documentElement) {
    return '';
  }

  var selector = '';

  if (element.tagName) {
    selector = element.tagName;
  }

  if (element.parentNode) {
    var index = Array.from(element.parentNode.children).indexOf(element) + 1;
    selector += ':nth-child(' + index + ')';
  }

  var parentSelector = getSelector(element.parentNode as HTMLElement);
  if (parentSelector) {
    selector = parentSelector + '>' + selector;
  }

  return selector.trim();
};
