<template>
  <b-container fluid style="height: 100vh">
    <b-row v-if="errorText || soundsLoaded < totalSounds">
      <b>{{ errorText }}</b>
      <br>
      Loaded {{ soundsLoaded }} of {{ totalSounds }} sound files...
    </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: [],
      bgSound: null,
      soundsLoaded: 0,
      errorText: null,
      columnWidth: 6
    }
  },
  computed: {
    totalSounds() {
      return this.availableSounds.length + 1 // because bg
    }
  },
  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

        if (this.nowPlaying !== -1) {
          this.availableSounds[this.nowPlaying].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,
        onload: () => this.soundsLoaded++,
        preload: true,
        onloaderror: (id, err) => this.errorText = id + err
      })

      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
            },
            onload: () => this.soundsLoaded++,
            preload: true,
            onloaderror: (id, err) => this.errorText = `${id} ${err}`
          })
        })
      })

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

<style scoped>

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

</style>