import { Howl } from 'howler'

let howl = null
let listeners = {}

function formatTime(secs) {
  if (!secs || isNaN(secs)) return '0:00'
  const m = Math.floor(secs / 60)
  const s = Math.floor(secs % 60)
  return `${m}:${s.toString().padStart(2, '0')}`
}

function load(url) {
  destroy()
  howl = new Howl({
    src: [url],
    html5: true,
    onplay: () => listeners.onPlay?.(),
    onpause: () => listeners.onPause?.(),
    onend: () => listeners.onEnd?.(),
    onloaderror: () => listeners.onError?.(),
    onplayerror: () => listeners.onError?.(),
  })
}

function play() { howl?.play() }
function pause() { howl?.pause() }
function togglePlay() { howl?.playing() ? howl.pause() : howl.play() }

function seek(time) { if (howl) howl.seek(time) }
function getSeek() { return howl ? howl.seek() : 0 }

function volume(val) {
  if (val !== undefined) Howler.volume(val / 100)
  return Howler.volume() * 100
}

function duration() { return howl ? howl.duration() : 0 }
function playing() { return howl ? howl.playing() : false }

function on(event, fn) { listeners[event] = fn }
function off(event) { delete listeners[event] }

function destroy() {
  if (howl) {
    howl.unload()
    howl = null
  }
  listeners = {}
}

export default {
  load, play, pause, togglePlay,
  seek, getSeek, volume, duration, playing,
  on, off, destroy, formatTime,
}
