<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,
    };
  },
  unmounted() {
    eventBus.$off("play:now");
  },
  mounted() {
    eventBus.$on("play:now", (url, metadata) => {
      this.play(url, metadata);
    });
    eventBus.$on("play:pause", () => {
      if (this.player) {
        this.player.pause();
      }
    });
    eventBus.$on("play:resume", () => {
      if (this.player) {
        this.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],
      });
      for (const eventName of ["pause", "play", "end"]) {
        newPlayer.on(eventName, this.updateStatusFromPlayer);
      }
      newPlayer.once("play", () => {
        if (this.player) {
          this.player.stop();
          this.player.unload();
        }
        this.player = newPlayer;
        if (metadata !== undefined) {
          this.title = metadata.title;
          this.live = metadata.live;
        }
        this.loading = false;
        this.updateStatusFromPlayer();
      });
      newPlayer.play();
    },
    stop() {
      if (this.player) {
        this.player.stop();
      }
      this.$refs.button.stop();
    },
  },
};
</script>
