import { RefObject } from 'react'

import size from 'lodash/size'

/**
 * Возвращает значение отрезка буфера которое ближе
 * к проигрываемому времени
 */
const getLoadedSeconds = (video: HTMLVideoElement | null) => {
  const bufferLength = size(video?.buffered)
  if (!video || bufferLength === 0) return 0

  for (let i = 0; i < bufferLength; i++) {
    const bufferPosition = bufferLength - 1 - i
    if (video.buffered.start(bufferPosition) < video.currentTime) {
      return video.buffered.end(bufferPosition)
    }
  }
  return 0
}

type Args = {
  onLoadedProgress?: (millis: number) => void,
  onPlayedProgress?: (millis: number) => void,
  videoRef: RefObject<HTMLVideoElement>,
}

export const useProgressChange = ({
  onLoadedProgress,
  onPlayedProgress,
  videoRef,
}: Args) => {
  const handleLoadedChange = () => {
    const loadedSeconds = getLoadedSeconds(videoRef.current)
    onLoadedProgress?.(loadedSeconds * 1000)
  }

  const handlePlayedChange = () => {
    const video = videoRef.current
    if (!video) return
    onPlayedProgress?.(video.currentTime * 1000)
  }

  return {
    handleLoadedChange,
    handlePlayedChange,
  }
}
