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

const useTraineeViewData = ({
  teamId,
  exerciseId,
}: {
  teamId?: string
  exerciseId: string
}) => {
  const [{ data, fetching: loading, error }] = useTypedQuery({
    query: GetTraineeViewData,
    variables: {
      teamId: teamId || '',
      exerciseId,
    },
    pause: !teamId,
  })

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

  return {
    loading: loading,
    error: error,
    team: data?.team || undefined,
    showExerciseTime:
      data?.exerciseId.config.enabledFeatures.includes('SHOW_EXERCISE_TIME') ||
      false,
    emailsEnabled,
    channels,
  }
}

export default useTraineeViewData
