import { useEffect, useState } from 'react'

import find from 'lodash/find'

import Hls, { MediaPlaylist } from 'hls.js'

export const useAudioTrack = (hls: Hls | null) => {
  const [audioTracks, setAudioTracks] = useState<Array<MediaPlaylist>>()
  const [selectedAudioTrack, setSelectedAudioTrack] = useState<MediaPlaylist>()

  const changeAudioTrack = (trackId: number) => {
    if (!hls) return

    // eslint-disable-next-line no-param-reassign
    hls.audioTrack = trackId
    const track = find(audioTracks, { id: trackId })

    setSelectedAudioTrack(track)
  }

  useEffect(() => {
    if (!hls) return undefined

    const listener = () => {
      const defaultTrack = find(hls.audioTracks, { id: selectedAudioTrack?.id })
        ?? find(hls.audioTracks, { default: true })

      setAudioTracks(hls.audioTracks)
      setSelectedAudioTrack(defaultTrack)
    }
    hls.on(Hls.Events.AUDIO_TRACK_LOADED, listener)

    return () => {
      hls.off(Hls.Events.AUDIO_TRACK_LOADED, listener)
    }
  }, [hls, selectedAudioTrack])

  return {
    audioTracks,
    changeAudioTrack,
    selectedAudioTrack,
  }
}
