import { useCallback, useRef } from 'react'

import { reportPlayerProgress } from 'requests'

import {
  useSportNameParam,
  usePageId,
  useInterval,
} from 'hooks'

const reportRequestInterval = 30000

export const usePlayerProgressReporter = () => {
  const { sportType } = useSportNameParam()
  const matchId = usePageId()
  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 }
}
