import { useEffect, useState } from 'react'
import { getSound } from 'requests/getSound'
import { readToken } from 'helpers'

export const useAudioPlayer = (id: number | string) => {
  const [audio, setAudio] = useState<HTMLAudioElement>()
  const [playing, setPlaying] = useState(false)

  const toggle = () => {
    setPlaying(!playing)
  }

  useEffect(() => {
    getSound(id).then(({ asset }) => {
      setAudio(new Audio(`${asset}?access_token=${readToken()}`))
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id])

  useEffect(() => {
    if (!audio) return
    playing ? audio.play() : audio.pause()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [playing, audio])

  useEffect(() => {
    audio?.addEventListener('ended', () => setPlaying(false))
    return () => {
      audio?.removeEventListener('ended', () => setPlaying(false))
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return { playing, toggle }
}
