import type { TeamStateMap } from '@/clientsettings/vars/teams'
import { teamStateMap, useTeamStateMap } from '@/clientsettings/vars/teams'
import { useGetRunningExercises } from '@inject/graphql/queries/GetRunningExercises.generated'
import notEmpty from '@inject/shared/utils/notEmpty'

const useTeamStateValidator = () => {
  const teamStateMapVar = useTeamStateMap()

  const { refetch } = useGetRunningExercises({
    fetchPolicy: 'network-only',
  })

  return async () => {
    const { data } = await refetch()
    if (!data || !data.exercises) return
    const runningExercises = data.exercises.filter(notEmpty)

    if (runningExercises.length === 0 || !data.exercises[0]) {
      /*
       * if the teamStateMapVar is not empty, the viewed exercise finished
       * or was paused
       *
       * keep the team state map but mark all teams as inactive
       */
      teamStateMap(
        Object.fromEntries(
          Object.entries(teamStateMapVar).map(([key, value]) => [
            key,
            { ...value, inactive: true },
          ])
        )
      )
      return
    }

    const newTeamStateMap: TeamStateMap = Object.fromEntries(
      data.exercises.filter(notEmpty).flatMap(exercise =>
        exercise.teams.map(team => [
          team.id,
          {
            team,
            show: false,
            inactive: false,
          },
        ])
      )
    )
    /*
     * if the teamStateMapVar is not empty, a previously selected exercise was
     * paused and is now running again
     *
     * keep the teams from the currently running exercises, but mark them
     * as active
     */
    const oldTeamStateMap: TeamStateMap = Object.fromEntries(
      Object.entries(teamStateMapVar)
        .filter(([, value]) =>
          runningExercises.some(
            exercise => exercise.id === value.team.exercise.id
          )
        )
        .map(([key, value]) => [
          key,
          {
            ...value,
            inactive: false,
          },
        ])
    )

    teamStateMap({
      ...newTeamStateMap,
      ...oldTeamStateMap,
    })
  }
}

export default useTeamStateValidator
