import { useTypedQuery } from '@inject/graphql/graphql'
import { GetTraineeViewData } from '@inject/graphql/queries'
import { useMemo } from 'react'

const useTraineeViewData = (exerciseId: string, teamId?: string) => {
  const [{ data, error }] = useTypedQuery({
    query: GetTraineeViewData,
    variables: {
      exerciseId,
    },
    pause: !teamId,
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })

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

  return {
    error: error,
    team: data?.exerciseId.teams.find(team => team.id === teamId) || undefined,
    showExerciseTime:
      data?.exerciseId.config.enabledFeatures.includes('SHOW_EXERCISE_TIME') ||
      false,
    emailsEnabled,
    channels,
  }
}

export default useTraineeViewData
