<template>
<f7-toolbar style='position: fixed; height: 80px;' bottom v-if="status != 'empty'">
  <!--
    il player avra' due stati aperto e chiuso? non so quanto mi piace, mi sembra che 
    le informazioni utili possano stare benissimo in questa toolbar.
    nel caso cmq bisogna fare una classe css per questi stati con l'altezza che varia.
  -->
  <f7-block>
    <f7-icon class='cursor-pointer' to='#' size='52px' f7='play_circle' @click="onPlay" v-if="!loading && status == 'pause'" />
    <f7-icon class='cursor-pointer' size='52px' f7='pause_circle' @click="onPause" v-if="!loading && status == 'playing'" />
    <f7-preloader size='42px' color='white' v-if='loading'/>
  </f7-block>
  <f7-block>
    <f7-link v-if='!loading'>{{title}}</f7-link>
  </f7-block>

</f7-toolbar>
</template>

<script>
import eventBus from '../js/eventBus'

import { Howl } from 'howler'

export default {
  components: { },
  data () {
    return {
      loading: true,
      status: 'empty',
      volume: 100,
      title: 'RadioBlackout > DIRETTA',
      subtitle: '',
      live: true,
      player: null
    }
  },
  destroyed () {
    eventBus.$off('play:now')
  },
  mounted () {
    const t = this
    eventBus.$on('play:now', function (url, metadata) {
        t.play(url, metadata)
        })
    eventBus.$on('play:pause', function() {
        if(t.player) {
          t.player.pause()
        }
        })
    eventBus.$on('play:resume', function() {
        if(t.player) {
          t.player.play()
        }
        })
  },
  methods: {
     onPlay() {
       eventBus.$emit('play:resume')
     },
     onPause() {
       eventBus.$emit('play:pause')
     },
   updateStatusFromPlayer () {
     this.status = this.player.playing() ? 'playing' : 'pause'
   },
    play (url, metadata) {
      this.loading = true
      let newPlayer = new Howl({
        autoSuspend: false,
        html5: true,
        preload: true,
        src: Array.isArray(url) ? url : [url],
      })
      const t = this
      for(const eventName of ['pause', 'play', 'end']) {
        newPlayer.on(eventName, this.updateStatusFromPlayer)
      }
      newPlayer.once('play', function setProperData() {
        if(t.player) {
          t.player.stop()
          t.player.unload()
        }
        t.player = newPlayer
        if(metadata !== undefined) {
          t.title = metadata.title
          t.live = metadata.live
        }
        t.loading = false
        t.updateStatusFromPlayer()
      })
      newPlayer.play()

    },
    stop () {
      if (this.player) {
        this.player.stop()
      }
      this.$refs.button.stop()
    },
  }
}
</script>

