<!-- eslint-disable vue/no-multiple-template-root -->
<template>
  <h4> Die Audio HowlWebAudioBridge sorgt zwar für ein sauberes Streaming, aber lässt sich dann nicht über WebAudio regeln</h4>
  <div>
    <HowlWebAudioBridge
      :src="source"
      :audio-context="audioContext"
      :on-ready="handleAudioNode"
    />
    <button @click="testAudio">Test Audio</button>
  </div>
</template>

<script setup lang="ts">
import HowlWebAudioBridge from '~/components/Player/HowlWebAudioBridge.vue'
import tracksConfig from '~/tracks.config'
import { useAudioStore, ensureAudio } from '~/stores/audio'

const audioContext = useAudioStore().getContext()
const source = tracksConfig.debug_src
const audioNode = ref({} as AudioBufferSourceNode | MediaElementAudioSourceNode | MediaStreamAudioSourceNode)
const gainNode = ref({} as GainNode)
const audioReady = ref(false as boolean)
const howlElement = ref({} as Howl)

async function testAudio () {
  await ensureAudio()
  if (audioReady && gainNode && howlElement) {
    howlElement.value.play()
    const audioDestination = audioContext.destination
    const gain = gainNode.value as GainNode
    if (audioNode instanceof AudioBufferSourceNode) {
      audioNode.loop = true
      audioNode.playbackRate.value = 1
      audioNode.connect(gain).connect(audioDestination)
    }
    if (audioNode instanceof MediaElementAudioSourceNode) {
      audioNode.connect(gain).connect(audioDestination)
    }
    if (audioNode instanceof MediaStreamAudioSourceNode) {
      audioNode.connect(gain).connect(audioDestination)
    }
    gain.gain.cancelScheduledValues(audioContext.currentTime)
    gain.gain.linearRampToValueAtTime(1, audioContext.currentTime + 2)

    useNuxtApp().$logger.log('Gain connected to destination')
  } else {
    useNuxtApp().$logger.warn('Audio is not yet ready to test it')
  }
}

function handleAudioNode (node: MediaElementAudioSourceNode | AudioBufferSourceNode | MediaStreamAudioSourceNode, howl: Howl | null) {
  useNuxtApp().$logger.log('AUDIONODE IST ANGEKOMMEN ')
  useNuxtApp().$logger.log({ node })
  useNuxtApp().$logger.log({ howl })
  audioNode.value = node
  if (howl) { howlElement.value = howl }

  gainNode.value = audioContext.createGain() as GainNode
  gainNode.value.gain.setValueAtTime(0, audioContext.currentTime)

  // Not connected to any destination, gain currently muted
  if (node instanceof AudioBufferSourceNode) {
    node.loop = true
    node.playbackRate.value = 1
    node.connect(gainNode.value)
  }
  if (node instanceof MediaElementAudioSourceNode) {
    node.connect(gainNode.value)
  }
  if (node instanceof MediaStreamAudioSourceNode) {
    node.connect(gainNode.value)
  }
  audioReady.value = true
}

</script>
