<template>
  <b-container fluid style="height: 100vh">
    <b-row v-if="errorCondition">
      {{ errorCondition }}
    </b-row>
    <b-row v-else class="mb-2 h-100">
      <b-col v-for="(snd,id) in availableSounds" :key="id" class="my-2" :cols="columnWidth" align-v="stretch">
        <b-button @click="play(id)" squared size="lg" class="bigBoyButton"
                  :variant="nowPlaying === id? 'success' : 'secondary'">
          {{ snd.sampleName }}
        </b-button>
      </b-col>
    </b-row>
  </b-container>
</template>

<script>
import {Howl} from 'howler'
import axios from 'axios'

export default {
  name: 'Home',
  data() {
    return {
      nowPlaying: -1,
      availableSounds: [],
      columnWidth: 6,
      errorCondition: false,
      bgSound: null
    }
  },
  methods: {
    play(sampleId) {

      const sample = this.availableSounds[sampleId].howl

      if (sample.playing()) {
        sample.stop()
        this.nowPlaying = -1
        this.bgSound.play() // Continue background sound

      } else {
        this.bgSound.pause() // the background sound must be paused

        this.availableSounds.forEach((snd) => { // Stop all other effects
          snd.howl.stop()
        })

        sample.play()
        this.nowPlaying = sampleId
      }

    }
  },
  mounted() {
    axios.get(process.env.VUE_APP_INDEX_URL).then((response) => {
      this.columnWidth = response.data['columnWidth'] || 6
      this.bgSound = new Howl({
        src: response.data['bg'],
        loop: true
      })

      response.data['availableSounds'].forEach((sndData) => {
        this.availableSounds.push({
          sampleName: sndData.sampleName,
          howl: new Howl({
            src: [sndData.url],
            loop: false,
            onend: () => {
              this.nowPlaying = -1
              this.bgSound.play() // Continue background sound
            }
          })
        })
      })

    }).catch((err) => this.errorCondition = err)
  }
}
</script>

<style scoped>

.bigBoyButton {
  width: 100%;
  height: 100%;
}

</style>