import { ref, watchEffect } from 'vue';

export function useAsyncQueue() {
  const queue: Fn<any, Promise<any>>[] = [];

  const executeFlag = ref(false);

  const setTask = (fn: Fn<any, Promise<any>>) => {
    queue.push(fn);
  };

  const removeTask = (fn: Fn<any, Promise<any>>) => {
    const index = queue.findIndex((item) => item === fn);
    ~index && queue.splice(index, 1);
  };

  const clearTask = () => {
    queue.length = 0;
  };

  watchEffect(() => {
    if (executeFlag.value) {
      queue.forEach((item) => item());
      executeFlag.value = false;
      clearTask();
    }
  });

  return { setTask, removeTask, clearTask, executeFlag };
}
