<template>
  <h3> AudioTagWebAudio </h3>
  <p>In diesem Test funktioniert die Messung der db</p>
  <button @click="fetchAudio">Fetch </button> <br> fetched:{{ readyState }}<br><br>
  <button v-if="readyState" @click="startAudio">  Play </button> gain:<p v-if="gainNode"> {{ gainNode }} </p>
  <div v-if="audioNodes.length > 0">
    <!-- eslint-disable-next-line vue/require-v-for-key -->
    <div v-for="node in audioNodes">
      state: {{ node.state() }} <br>
      src: {{ node._src }} <br>
      playing: {{ node.playing() }} <br>
      webaudio: {{ node._webAudio }} <br>
      duration: {{ node.duration() }} <br>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, watch, computed } from 'vue'
import { createStreamingAudioSource } from '~/lib/AudioFunctions'
import { useAudioStore } from '~/stores/audio'

export default defineComponent({
  name: 'AudioTagWebAudio',
  props: {
    src: {
      type: String,
      required: true
    },
    volume: {
      type: Number,
      default: 0.5
    }
  },
  emits: ['canplay'],
  setup (props, { emit: $emit }) {
    const ctx = useAudioStore().getContext()
    const readyState = ref(false)
    const fadingState = ref(false)
    const audioNodes = ref([] as Array<Howl>)

    const safeVolume = computed((): Number => {
      const volumeVal = props.volume as number
      if (volumeVal >= 0 && volumeVal <= 1) { return volumeVal }
      return Math.abs(volumeVal - 0) < Math.abs(volumeVal - 1) ? 0 : 1
    })

    let gainNode: GainNode | null = null
    let audioElement: Howl | null = null

    const emitReady = () => {
      $emit('canplay')
    }
    const connectGainNode = (source:AudioBufferSourceNode) => {
      gainNode = ctx.createGain()

      gainNode.gain.setValueAtTime(0, ctx.currentTime)
      source.connect(gainNode)

      gainNode.connect(ctx.destination)
    }
    const fetchAudio = async () => {
      audioElement = null
      useNuxtApp().$logger.log('PFAD: ' + props.src)
      audioElement = await createStreamingAudioSource(ctx, props.src)
      audioNodes.value.push(audioElement)
      if (audioElement instanceof Howl) {
        audioElement.volume(props.volume)
        audioElement?.play()
        useNuxtApp().$logger.log({ audioElement })
        readyState.value = true
        emitReady()
      }
      useNuxtApp().$logger.log('gefetchtes audioElement', { audioElement })
    }
    const startAudio = () => {
      useNuxtApp().$logger.log('start Audio')
      audioElement?.mute()
    }

    watch(() => props.volume, () => {
      audioElement?.volume(props.volume)
    })

    return {
      safeVolume,
      emitReady,
      fetchAudio,
      readyState,
      fadingState,
      startAudio,
      gainNode,
      audioNodes
    }
  }
})
</script>
