import { WatchSource } from 'vue'

export function useLoop(
  loopFunctions: (() => void | Promise<void>)[],
  interval: number | string,
  watchSources: (WatchSource | object)[] = []
) {
  let queryLoop: number | null = null
  let querying = false
  let stopFlag = false
  const startQuery = async () => {
    querying = true
    stopFlag = false

    await Promise.allSettled(loopFunctions.map(func => func()))
    if (stopFlag) {
      return
    }
    queryLoop = window.setTimeout(
      startQuery,
      typeof interval === 'string'
        ? LOOP_INTERVAL[interval]
          ? LOOP_INTERVAL[interval]
          : 15 * 1000
        : interval
    )
  }
  const stopQuery = () => {
    stopFlag = true
    if (queryLoop) {
      clearTimeout(queryLoop)
      queryLoop = null
    }
    querying = false
  }
  if (watchSources.length) {
    watch(watchSources, () => {
      stopQuery()
      startQuery()
    })
  }
  onMounted(() => {
    if (querying) {
      return
    }
    startQuery()
  })
  onActivated(() => {
    if (querying) {
      return
    }
    startQuery()
  })
  onDeactivated(() => {
    stopQuery()
  })
  onBeforeUnmount(() => {
    stopQuery()
  })
}
