<template>
  <div class="noise-controlled-band">
    <AudioTag
      :ref="el => audioElement"
      :src="audioSrc"
      :volume="volume"
      :play="playing"
      @canplay="onCanPlay"
    />
    <RNBOControlValue
      :center-frequency="centerFrequency"
      :status="playing"
      :q-factor="$props.qFactor"
      :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
    },
    qFactor: {
      type: Number,
      required: true
    },
    masterAttack: {
      type: Number,
      default: 120000,
      required: false
    },
    masterRelease: {
      type: Number,
      default: 144000,
      required: false
    }
  },
  emits: ['ready', 'update:mid-volume'],
  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 frequency = props.centerFrequency

        let band = ''
        if (frequency < 500) {
          band = 'low_band'
        } else if (frequency >= 500 && frequency < 4000) {
          band = 'mid_band'
        } else {
          band = 'high_band'
        }

        const path = `/masking/3bands/${band}_256kbps.webm`
        const fullPath = `${window.location.origin}${encodeURI(path)}`

        useNuxtApp().$logger.info('Loading audio track:', fullPath)

        return fullPath
      } 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
      emit('update:mid-volume', volume.value)
    }

    const onCanPlay = () => {
      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>
