import { useEffect, useCallback } from 'react'
import { audioController, sounds } from '../audio/AudioController'
import { createSound, stopAllSounds } from '../audio/ExtendedHowl'

export function useAudio() {
  useEffect(() => {
    return () => audioController.stop()
  }, [])

  const load = useCallback((url: string) => audioController.load(url), [])
  const play = useCallback(() => audioController.play(), [])
  const pause = useCallback(() => audioController.pause(), [])
  const stop = useCallback(() => audioController.stop(), [])
  const toggle = useCallback(() => audioController.toggle(), [])
  const toggleMute = useCallback(() => audioController.toggleMute(), [])
  const stopAll = useCallback(() => stopAllSounds(), [])
  const playNew = useCallback((url: string) => {
    const howl = createSound(url)
    if (howl) audioController.stopAllAndPlay(howl)
  }, [])

  return { load, play, pause, stop, toggle, toggleMute, stopAll, playNew, sounds, audioController }
}
