<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'
import _ from 'lodash'

export default {
  name: 'Home',
  data() {
    return {
      nowPlaying: -1,
      availableSounds: [],
      bgSound: null,
      soundsLoaded: 0,
      errorText: null,
      columnWidth: 6,
      sequence: [],
      sequenceCleanerTimeout: null
    }
  },
  computed: {
    totalSounds() {
      return this.availableSounds.length + 1 // because bg
    }
  },
  methods: {
    patternMagic(sampleId) {
      this.sequence.push(sampleId)

      if (this.sequence.length > 4) {
        this.sequence.shift() // removes the first element from an array
      }

      if (_.isEqual(this.sequence, [0, 1, 3, 2])) {
        const elem = document.documentElement

        if (elem.requestFullscreen) {
          elem.requestFullscreen();
        } else if (elem.webkitRequestFullscreen) { /* Safari */
          elem.webkitRequestFullscreen();
        } else if (elem.msRequestFullscreen) { /* IE11 */
          elem.msRequestFullscreen();
        }

        this.sequence = []
      }

      if (_.isEqual(this.sequence, [0, 3, 3, 0])) {
        location.reload()
        this.sequence = []
      }

      if (_.isEqual(this.sequence, [0, 3, 1, 1])) {
        this.bgSound.stop()
        this.availableSounds[this.nowPlaying].howl.stop()
        this.nowPlaying = -1
        this.sequence = []
        return true;
      }

      // Set timer to clear sequence
      if (this.sequenceCleanerTimeout !== null) {
        clearTimeout(this.sequenceCleanerTimeout)
      }
      this.sequenceCleanerTimeout = setTimeout(() => {
        this.sequence = []
        this.sequenceCleanerTimeout = null
      },3000)

      return false;
    },
    play(sampleId) {
      const prevent = this.patternMagic(sampleId)

      if (prevent) {
        return;
      }

      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>