<template>
  <div v-show="false">
    <h1>Microphone</h1>
    <button @click="attach">
      {{ microphoneActive ? 'Mikrofon trennen' : 'Mikrofon aktivieren' }}
    </button>
  </div>
</template>
<script lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useAudioStore } from '~/stores/audio'
import { useMicStore } from '~/stores/microphone'
export default {
  name: 'MicrophoneHandler',
  emits: ['update:attach'],
  setup (_props, { emit }) {
    const audioStore = useAudioStore()
    const microphone = ref<Promise<MediaStream> | null>(null)
    const microphoneActive = ref(false)

    const attach = () => {
      if (!microphone.value) {
        microphone.value = navigator.mediaDevices.getUserMedia({
          audio: {
            echoCancellation: false,
            noiseSuppression: false,
            autoGainControl: false
          },
          video: false
        })
        microphoneActive.value = true
      }

      return microphone.value.then((stream) => {
        // useNuxtApp().$logger.log('stream there' + stream)
        emit('update:attach', stream)
        return stream
      })
    }

    const detach = async () => {
      if (microphone.value) {
        try {
          const stream = await microphone.value
          stream.getTracks().forEach(track => track.stop())
        } catch (error) {
        }
        microphone.value = null
        microphoneActive.value = false
      }
    }

    watch(() => audioStore.playing, (newValue) => {
      if (newValue) {
        attach()
      } else {
        detach()
      }
    })

    onUnmounted(() => {
      // Clean up by detaching the microphone when the component is unmounted
      detach()
    })

    // Return the public properties and methods
    return {
      attach,
      detach,
      isPlaying: () => audioStore.playing,
      microphoneActive
    }
  }
}
</script>
