import { useGetExerciseChannels } from '@inject/graphql/queries/GetExerciseChannels.generated'
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,
    loading: channelsLoading,
    error: channelsError,
  } = useGetExerciseChannels({
    variables: { exerciseId: exerciseId || '' },
    skip: !exerciseId,
  })
  const {
    data: loopData,
    loading: 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
