<template>
  <div>
    <KeyboardPlayHandler />
    <h1> Test Fall 2 mit Control Value Patch</h1>
    <h2>Use AudioBufferSourceNode over controlled NoiseControlledWebAudioBand</h2>
    <h3> press space to start</h3>
    <div>
      Masking Gain : <input
        id="gain-control"
        :onchange="updateMasterGain"
        type="range"
        min="0"
        max="1"
        step="0.01"
      >
    </div>
    <div v-if="loading" class="spinner-border spinner-border-sm" role="status">
      <span class="sr-only">{{ t("Loading...") }}</span>
    </div>
    Loaded Bands: {{ loadedBands }}
    <NoiseControlledWebAudioBand
      v-for="frequency in frequencies"
      v-show="false"
      :key="frequency"
      :center-frequency="frequency"
      :master-gain="masterGainNode"
      @ready="onBandReady"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import KeyboardPlayHandler from '~/archive/components/KeyboardPlayHandler.vue'
import NoiseControlledWebAudioBand from '~/components/experiments/tests/ControlValues/NoiseControlledWebAudioBand.vue'
import { useAudioStore } from '~/stores/audio'

export default defineComponent({
  components: {
    NoiseControlledWebAudioBand,
    KeyboardPlayHandler
  },
  setup () {
    const { t } = useI18n()
    const frequencies = ref([63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000])
    const loadedBands = ref(0)
    const masterGainNode = computed(() => { return useAudioStore().getMasterGainNoise() })
    const masterAttack = ref(120000 * 2) // Beispielwert in Samples
    const masterRelease = ref(144000 * 2)
    const loading = computed(() => loadedBands.value < frequencies.value.length)

    const updateMasterGain = (changeEvent:Event) => {
      const newValue = changeEvent?.target as any
      masterGainNode.value.gain.linearRampToValueAtTime(newValue.value, masterGainNode.value.context.currentTime + 0.25)
    }
    const onBandReady = () => {
      loadedBands.value++
    }

    return {
      frequencies,
      loading,
      onBandReady,
      t,
      loadedBands,
      masterGainNode,
      updateMasterGain,
      masterAttack,
      masterRelease
    }
  }
})
</script>
