import { watch } from "vue";

export const watchPolling = <T>(
  getStart: () => { start: boolean; payload: T },
  task: (payload: T) => void
) => {
  let timeout: number;
  let stop = false;

  const cleanup = () => {
    clearTimeout(timeout);
    stop = true;
  };

  const stopWatch = watch(
    getStart,
    ({ start, payload }, _, onCleanup) => {
      if (!start) {
        return;
      }
      stop = false;
      const pollingTask = async () => {
        await task(payload);
        if (!stop) {
          timeout = setTimeout(pollingTask, 3000);
        }
      };

      pollingTask();
      onCleanup(cleanup);
    },
    { immediate: true }
  );

  return () => {
    cleanup();
    stopWatch();
  };
};
