<template>
    <div>
      <button @click="startMicrophone">Start Microphone</button>
      <button @click="stopMicrophone">Stop Microphone</button>
      <canvas ref="visualizationCanvas" width="800" height="200"></canvas>
      <div v-if="errorMessage">{{ errorMessage }}</div>
    </div>
  </template>
  
  <script>
  export default {
    data() {
      return {
        audioContext: null,
        microphoneStream: null,
        audioProcessorNode: null,
        errorMessage: null,
      };
    },
    methods: {
      async startMicrophone() {
        try {
          this.initializeAudioContext();
          await this.requestMicrophoneAccess();
          await this.setupAudioProcessing();
        } catch (error) {
          console.error('Error starting microphone:', error.message);
          this.errorMessage = error.message;
        }
        finally{
          console.log("Microphone started")
        }
      },
      stopMicrophone() {
        this.cleanup();
      },
      initializeAudioContext() {
        this.audioContext = new window.AudioContext();
      },
      async requestMicrophoneAccess() {
        try {
          this.microphoneStream = await navigator.mediaDevices.getUserMedia({ audio: true });
        } catch (error) {
          console.error('Error accessing microphone:', error.message);
          this.errorMessage = 'Microphone access denied. Please grant permission in your browser settings.';
          throw new Error('Microphone access denied.');
        }
  
        if (!this.microphoneStream || !(this.microphoneStream instanceof MediaStream)) {
          throw new Error('Microphone stream is not available.');
        }
      },
      async setupAudioProcessing() {
    try {
      const microphoneSource = this.audioContext.createMediaStreamSource(this.microphoneStream);
      await this.audioContext.audioWorklet.addModule('/scripts/octave2.js');
  
      //this.audioProcessorNode = new AudioWorkletNode(this.audioContext, 'octave');
      //microphoneSource.connect(this.audioProcessorNode);
      //this.audioProcessorNode.connect(this.audioContext.destination);
    } catch (error) {
      console.error('Error setting up audio processing:', error.message);
      this.errorMessage = 'Error setting up audio processing. Please check your microphone and try again.';
      throw new Error('Audio processing setup failed.');
    }
    },
      cleanup() {
        if (this.audioContext) {
          if (this.audioProcessorNode) {
            this.audioProcessorNode.disconnect();
            this.audioProcessorNode.port.postMessage({ command: 'stop' });
          }
          this.audioContext.close();
          this.resetVariables();
        }
      },
      resetVariables() {
        this.audioContext = null;
        this.microphoneStream = null;
        this.audioProcessorNode = null;
        this.errorMessage = null;
      },
    },
    beforeDestroy() {
      this.cleanup();
    },
  };
  </script>
  