<template>
  <div v-show="true">
    <h1>Microphone</h1>
    <button class="btn btn-primary" @click="attach">
      {{ 'Mikrofon aktivieren' }}
    </button>
    <button class="btn btn-secondary" @click="detach">
      {{ 'Mikrofon trennen' }}
    </button>
  </div>
</template>
<script lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import type { Logger } from 'pino'
import { useMicStore } from '~/stores/microphone'
import { useAudioStore } from '~/stores/audio'

export default {
  name: 'MicrophoneStoreHandler',
  emits: ['update:attach'],
  setup (_props, { emit }) {
    const audioStore = useAudioStore()
    const microphone = ref<Promise<MediaStream> | null>(null)
    const microphoneActive = ref(false)
    const logger = useNuxtApp().$logger as Logger

    const attach = () => {
      logger.info('attach microphone')
      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) => {
        emit('update:attach', stream)
        return stream
      })
    }

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

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