import { useGetTraineeViewData } from '@inject/graphql/queries/GetTraineeViewData.generated'
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, loading, error } = useGetTraineeViewData({
    variables: { teamId, exerciseId },
  })
  const {
    data: loopData,
    loading: 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
