import { useCallback, useRef } from 'react'

import { reportPlayerProgress } from 'requests'

import { usePageParams } from 'hooks/usePageParams'
import { useInterval } from 'hooks/useInterval'

const reportRequestInterval = 30000

export const usePlayerProgressReporter = () => {
  const { profileId: matchId, sportType } = usePageParams()
  const playerData = useRef({ period: 0, seconds: 0 })

  const intervalCallback = () => {
    const { period, seconds } = playerData.current
    reportPlayerProgress({
      half: period,
      matchId,
      seconds,
      sport: sportType,
    })
  }
  const { start, stop } = useInterval({
    callback: intervalCallback,
    intervalDuration: reportRequestInterval,
    startImmediate: false,
  })

  const onPlayingChange = useCallback((playing: boolean) => {
    if (playing) {
      start()
    } else {
      stop()
    }
  }, [start, stop])

  const onPlayerProgressChange = useCallback((seconds: number, period = 0) => {
    playerData.current = { period, seconds }
  }, [])

  return { onPlayerProgressChange, onPlayingChange }
}
