import type { LocalChange } from 'injector/types';

type GetElementFromChangeFn = (change: LocalChange, body?: HTMLElement) => HTMLElement | null;
export const getElementFromChange: GetElementFromChangeFn = (change, body = document.body) => {
  try {
    let element = !!change.selector && body.querySelector(change.selector);
    if (element) {
      return element as HTMLElement;
    }

    try {
      if (!change.friendlySelector) return null;
      const elements = body.querySelectorAll(change.friendlySelector);
      if (elements.length === 1) {
        return elements[0] as HTMLElement;
      }
      if (elements.length > 1) {
        const index = change.friendlySelectorIndex;
        if (typeof index !== 'number') return null;
        if (elements[index]) {
          return elements[index] as HTMLElement;
        }
      }
    } catch (ex) {}
  } catch (ex) {}
  return null;
};
