<template>
  <div class="noise-controlled-band">
    <AudioTag
      :ref="el => audioElement"
      :src="audioSrc"
      :volume="volume"
      :play="playing"
      @canplay="onCanPlay"
    />
    <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 AudioTag from '../../AudioTag.vue'
import RNBOControlValue from '../../tests/ControlValues/RNBOControlValue.vue'
import tracksConfig from '~/tracks.config'
import { useAudioStore } from '~/stores/audio'
import { calculateNormalizedVolume } from '~/lib/AudioFunctions'

export default defineComponent({
  name: 'NoiseControlledBand',
  components: {
    AudioTag,
    RNBOControlValue
  },
  props: {
    centerFrequency: {
      type: Number,
      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 playing = computed(() => { return useAudioStore().playing }) // the playing state is bind to the audioStore
    const gainValueDB = ref(0)
    const volume = ref(0)
    const audioSrc = computed(() => {
      try {
        const frequencyKey = `${props.centerFrequency}_src`
        useNuxtApp().$logger.log('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) {
        useNuxtApp().$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 = () => {
      useNuxtApp().$logger.log(`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>
