<template>
  <div class="bday">
    <h1>Alles Gute zu Deinem Geburtstag!</h1>
    <div ref="plyrContainer" class="plyrContainer">
      <img
        ref="play"
        class="play"
        src="../assets/play.png"
        usemap="#play"
        v-show="playVisible"
        @click="playClicked"
      />
      <map name="#play">
        <area shape="circle" coords="50, 50, 50" @click="playClicked" />
      </map>
      <vue-plyr
        ref="plyr"
        :options="plyrOptions"
        :emit="['timeupdate', 'ready']"
        @timeupdate="videoTimeUpdated"
        @ready="videoLoaded"
      >
        <!-- inserted dynamically -->
        <video poster="../assets/poster.png" />
      </vue-plyr>
    </div>
  </div>
</template>

<script>
export default {
  name: "BDay",

  data: () => ({
    videoQueue: ["part1", "part2"],
    currentVideo: -1,

    playVisible: true,

    plyrOptions: {
      clickToPlay: false,
      keyboard: { focused: false, global: false },
      controls: ["mute", "volume", "settings", "airplay", "fullscreen"],
      settings: ["quality"],
    },
  }),

  computed: {
    player() {
      return this.$refs.plyr.player;
    },
  },

  methods: {
    getVideoSource: function (index) {
      let source = {
        type: "video",
        sources: [],
      };

      for (const height of [240, 360, 480]) {
        source.sources.push({
          src: "/fake_api/" + this.videoQueue[index] + "_" + height + ".mp4",
          type: "video/mp4",
          size: height,
        });
      }

      return source;
    },

    videoTimeUpdated: function () {
      // show play button after 3 seconds, then disable this event
      if (this.player.currentTime > 3) {
        this.playVisible = true;
        this.videoTimeUpdated = () => true;
      }
    },

    videoLoaded: function () {
      this.placePlay();
      if (this.currentVideo >= 0) {
        this.player.play();
      }
    },

    playClicked: function () {
      this.playVisible = false;

      this.currentVideo += 1;
      this.player.source = this.getVideoSource(this.currentVideo);
    },

    placePlay: function () {
      let top = (this.$refs.plyrContainer.offsetHeight - 100) / 2;
      let left = (this.$refs.plyrContainer.offsetWidth - 100) / 2;

      console.log(left, top);

      this.$refs.play.style.top = top + "px";
      this.$refs.play.style.left = left + "px";
    },
  },

  mounted() {
    document.title = "Herzlichen Glückwunsch!";
    window.addEventListener("resize", this.placePlay);
  },
};
</script>

<style scoped>
div.bday {
  margin: auto;
  max-width: 854px;
}

div.plyrContainer {
  position: relative;
}

img.play {
  outline: none;

  -webkit-user-select: none; /* Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE10+/Edge */
  user-select: none; /* Standard */

  position: absolute;
  z-index: 1001;
}

map area {
  outline: none;
  cursor: pointer;
}
</style>
