<template>
  <div class="noise-controlled-band">
    <AudioTagWebAudio
      ref="audioElement"
      :src="audioSrc"
      :volume="volume"
      :play="playing"
      :master-gain="masterGain"
      @canplay="onCanPlay"
    />
    Gain: {{ gainValueDB }}
    <RNBOControlValue
      :center-frequency="centerFrequency"
      :status="playing"
      :attack="masterAttack"
      :release="masterRelease"
      @control-value-change="handleValueChange"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed } from 'vue'
import type { Logger } from 'pino'
import RNBOControlValue from '../..//tests/ControlValues/RNBOControlValue.vue'
import AudioTagWebAudio from '../../AudioTagWebAudio.vue'
import tracksConfig from '~/tracks.config'
import { calculateNormalizedVolume } from '~/lib/AudioFunctions'
import { useAudioStore } from '~/stores/audio'

export default defineComponent({
  name: 'NoiseControlledWebAudioBand',
  components: {
    AudioTagWebAudio,
    RNBOControlValue
  },
  props: {
    centerFrequency: {
      type: Number,
      required: true
    },
    masterGain: {
      type: GainNode,
      required: true
    },
    masterAttack: {
      type: Number,
      default: 120000,
      required: false
    },
    masterRelease: {
      type: Number,
      default: 144000,
      required: false
    }
  },
  emits: ['ready'],
  setup (props, { emit }) {
    const audioElement = ref<InstanceType<typeof HTMLElement> | null>(null)
    const gainValueDB = ref(0)
    const volume = ref(1)
    const playing = computed(() => { return useAudioStore().playing }) // the playing state is bind to the audioStore
    const logger = useNuxtApp().$logger as Logger
    const audioSrc = computed(() => {
      try {
        const frequencyKey = `${props.centerFrequency}_src`
        logger.info('Loading audio track:', frequencyKey)
        const trackPath = tracksConfig[frequencyKey as keyof typeof tracksConfig]
        if (!trackPath) {
          throw new Error(`No track found for frequency ${props.centerFrequency}`)
        }
        const returnValue = `${window.location.origin}${encodeURI(trackPath)}`
        // Check if the audio file is available
        return returnValue
      } catch (error) {
        logger.error('Error loading audio track:', error)
        return ''
      }
    })
    const handleValueChange = (data: { frequency: number; value: number }) => {
      // Convert dB to linear scale
      gainValueDB.value = calculateNormalizedVolume(data.value)
      volume.value = gainValueDB.value
    }

    const onCanPlay = () => {
      logger.info(`Audio for frequency ${props.centerFrequency} is ready to play`)
      emit('ready', props.centerFrequency)
    }

    return {
      audioElement,
      audioSrc,
      gainValueDB,
      volume,
      handleValueChange,
      onCanPlay,
      playing
    }
  }
})
</script>

<style scoped>
.noise-controlled-band {
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 5px;
}
</style>
