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

const useTraineeViewData = ({
  teamId,
  exerciseId,
}: {
  teamId: string
  exerciseId: string
}) => {
  const [{ data, fetching: loading, error }] = useTypedQuery({
    query: GetTraineeViewData,
    variables: { teamId, exerciseId },
  })
  const [{ data: loopData, fetching: loopLoading, error: loopError }] =
    useExerciseLoopStatusSubscription(exerciseId)

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

  return {
    loading: loading || loopLoading,
    error: error || loopError,
    team: data?.team || undefined,
    showExerciseTime: data?.exerciseConfig?.showExerciseTime || false,
    emailsEnabled,
    channels,
    loopRunning: loopData?.exerciseLoopRunning || false,
  }
}

export default useTraineeViewData
