<template>
  <div class="howl-web-audio"> Howl as HTML5 with AudioNode - Node's ReadyState = {{ canPlay }} </div>
  <div v-if="canPlay" style="width: 2em; height: 2em; background-color:green;" />
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { Howl } from 'howler'
import type { Logger } from 'pino'
import { checkClipping, setupAudioSource } from '~/lib/AudioFunctions'

const logger = useNuxtApp().$logger as Logger

const props = defineProps<{
  src: string
  audioContext: AudioContext
  onReady?:(node: MediaElementAudioSourceNode | AudioBufferSourceNode | MediaStreamAudioSourceNode, howl: Howl | null) => void
}>()

let howl: Howl | null = null
let mediaElement: HTMLAudioElement | null = null
const mediaStreamSource: MediaElementAudioSourceNode | AudioBufferSourceNode | MediaStreamAudioSourceNode | null = null
const canPlay = ref(false)

onMounted(() => {
  // Initialisiere Howler im HTML5-Modus
  howl = new Howl({
    src: [props.src],
    html5: true,
    preload: true,
    onplay: () => {
      logger.info('howl is playing now')
    },
    onpause: () => { logger.info('howl is paused now') },
    onend: () => {
      logger.info('howl has ended now')
      canPlay.value = false
    },
    onload: async () => {
      // Zugriff auf das echte <audio> Element
      mediaElement = await (howl as any)._sounds[0]._node as HTMLAudioElement
      // mediaStreamSource = await setupAudioSource(mediaElement, props.audioContext)
      const mediaElementSource = props.audioContext.createMediaElementSource(mediaElement) // AudioNode spielt sofort
      logger.info('AudioNode sollte Ready sein', { mediaElementSource })
      if (mediaElementSource instanceof AudioNode) {
        // readyState = true
        props.onReady?.(mediaElementSource, howl)
        canPlay.value = true
      }
      logger.info('howl has loaded now')
    }
  })
})

onBeforeUnmount(() => {
  howl?.unload()
  canPlay.value = false
  // mediaStreamSource?.disconnect()
})
</script>

<style scoped>
button {
  padding: 0.5rem 1rem;
}
</style>
