import { effectScope, onScopeDispose, watch } from 'vue'
import uesFetch from '@/hooks/useFetch'
import useMainStore from '@/store/main'

import type { EffectScope, ShallowRef } from 'vue'
import type { ExtractApiResponse } from '@/api/api'

const useMessageLoop = () => {
  const mainStore = useMainStore()

  const { fetch: getUnReadMessage, result: unReadMessage, cancel } = uesFetch('getUnReadMessage')

  let timer: number | null = null

  const cleanTimer = () => {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
  }

  const getUnReadMessageFn = () => {
    getUnReadMessage()
    cleanTimer()
    timer = window.setTimeout(getUnReadMessageFn, 30 * 1000)
  }

  watch(
    () => mainStore?.myUserInfo?.role,
    () => {
      if (mainStore?.myUserInfo?.role && mainStore?.myUserInfo?.role !== 'ADMIN') {
        getUnReadMessageFn()
      }
    },
    {
      immediate: true,
    }
  )

  onScopeDispose(cleanTimer)

  return unReadMessage
}

function createSharedComposable(composable: typeof useMessageLoop) {
  let subscribers = 0
  let state: ShallowRef<ExtractApiResponse<'getUnReadMessage'>> | null | undefined
  let scope: EffectScope | null

  const dispose = () => {
    if (scope && --subscribers <= 0) {
      scope.stop()
      state = scope = null
    }
  }

  return () => {
    subscribers++
    if (!state) {
      scope = effectScope(true)
      state = scope.run<ShallowRef<ExtractApiResponse<'getUnReadMessage'>>>(composable)
    }
    onScopeDispose(dispose)
    return state
  }
}

export default createSharedComposable(useMessageLoop)
