import PQueue from 'p-queue';

export type QueueFunction<T> = () => Promise<T>;

export function usePQueue(option: {
  concurrency?: number;
  autoStart?: boolean;
}) {
  const queue = new PQueue(option);

  async function buildQueue<T>(functions: QueueFunction<T>[]): Promise<T[]> {
    try {
      const results: T[] = await queue.addAll(functions);
      return results;
    } catch (error) {
      console.error(error);
      stopQueue();
      throw error;
    }
  }

  function startQueue() {
    queue.start();
  }

  function stopQueue() {
    queue.pause();
    queue.clear();
  }

  return {
    buildQueue,
    startQueue,
    stopQueue,
  };
}
