import {
  useEffect,
  useMemo,
  useRef,
} from 'react'
import Hls from 'hls.js'

import isNumber from 'lodash/isNumber'

import { streamConfig } from '../config'

type useHlsPlayerType = {
  isLive?: boolean,
  resumeFrom?: number,
  src: string,
}

export const useHlsPlayer = ({
  isLive,
  resumeFrom,
  src,
}: useHlsPlayerType) => {
  const hls = useMemo(() => {
    if (!Hls.isSupported()) return null

    const newStreamConfig = { ...streamConfig }
    if (isNumber(resumeFrom)) {
      newStreamConfig.startPosition = resumeFrom
    }
    return new Hls(newStreamConfig)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [resumeFrom, src])

  const videoRef = useRef<HTMLVideoElement>(null)

  useEffect(() => {
    const video = videoRef.current
    if (!video || !hls) return

    hls.loadSource(src)
    hls.attachMedia(video)
  }, [src, hls])

  useEffect(() => () => hls?.destroy(), [hls])

  return {
    hls,
    isLive,
    videoRef,
  }
}
