import { wait } from "gs-base";

export interface IForWaitFindOption {
  minLen?: number;
  delay?: number;
  count?: number;
  by?: Element | Document;
}

export async function forWaitFind<T extends HTMLElement = HTMLElement>(selector: string, option?: IForWaitFindOption): Promise<T[]> {
  const { minLen = 1, delay = 50, count = 50, by = document } = option || {};
  for (let i = 0; i < count; i++) {
    const elements = by.querySelectorAll<T>(selector);
    if (elements.length >= minLen) {
      return Array.from(elements);
    }
    await wait(delay);
  }
}
