import { useEffect } from 'react'
import { useGetExerciseLoopStatus } from '../queries/GetExerciseLoopStatus.generated'
import type { ExerciseLoopRunning } from '../subscriptions/ExerciseLoopStatus.generated'
import { ExerciseLoopRunningDocument } from '../subscriptions/ExerciseLoopStatus.generated'

const useExerciseLoopStatusSubscription = (exerciseId?: string) => {
  const query = useGetExerciseLoopStatus({
    fetchPolicy: 'network-only',
    nextFetchPolicy: 'cache-and-network',
    variables: {
      exerciseId: exerciseId || '',
    },
    skip: !exerciseId,
  })
  const { subscribeToMore } = query

  useEffect(() => {
    if (exerciseId) {
      return subscribeToMore({
        document: ExerciseLoopRunningDocument,
        variables: { exerciseId },
        updateQuery: (prev, { subscriptionData }) => {
          const data = subscriptionData.data as unknown as ExerciseLoopRunning
          if (data.exerciseLoopRunning?.exerciseLoopRunning === undefined) {
            return prev
          }
          return {
            ...prev,
            exerciseLoopRunning: data.exerciseLoopRunning.exerciseLoopRunning,
          }
        },
      })
    }
  }, [exerciseId, subscribeToMore])

  return query
}

export default useExerciseLoopStatusSubscription
