import { useTypedQuery } from '@inject/graphql/graphql'
import { GetExerciseChannels } from '@inject/graphql/queries'
import useExerciseLoopStatusSubscription from '@inject/graphql/utils/useExerciseLoopStatusSubscription'
import notEmpty from '@inject/shared/utils/notEmpty'
import { useMemo } from 'react'

const useInstructorViewData = ({ exerciseId }: { exerciseId?: string }) => {
  const [
    { data: channelsData, fetching: channelsLoading, error: channelsError },
  ] = useTypedQuery({
    query: GetExerciseChannels,
    variables: { exerciseId: exerciseId || '' },
    pause: !exerciseId,
    requestPolicy: 'cache-first',
  })
  const [{ data: loopData, fetching: loopLoading, error: loopError }] =
    useExerciseLoopStatusSubscription(exerciseId || '')

  const channels = useMemo(
    () => channelsData?.exerciseChannels?.filter(notEmpty) || [],
    [channelsData?.exerciseChannels]
  )
  const emailsEnabled = useMemo(
    () => channels.some(channel => channel?.type === 'EMAIL'),
    [channels]
  )

  return {
    loading: channelsLoading || loopLoading,
    error: channelsError || loopError,
    emailsEnabled,
    channels,
    loopRunning: loopData?.exerciseLoopRunning || false,
  }
}

export default useInstructorViewData
