<template>
  <div class="player">
    <youtube
      ref="youtube"
      :video-id="roomStatus.current.linkID"
      :player-vars="playerVars"
      @playing="roomStatus.player.playing">
    </youtube>
    <hr>
    <b-field position="is-centered">
        <b-button class="playerButton" @click="play" size="is-large" :icon-right="roomStatus.player.playing ? 'pause' : 'play'" :disabled="!(isAdmin || roomSettings.userControl)"/>
        <b-button class="playerButton" @click="mute" size="is-large" icon-right="volume-mute"/>
        <b-button class="playerButton" @click="skip" size="is-large" icon-right="skip-next" :disabled="!(isAdmin || roomSettings.userControl)"/>
        <b-slider class="playerVolume" size="is-large" :min="0" :max="100" :value="100" @change="volume"/>
    </b-field>
    <b-field position="is-centered">
      <b-slider
        rounded
        size="is-medium"
        :min="0"
        :max="roomStatus.player.timeLength"
        :value="roomStatus.player.timeCode"
        :custom-formatter="value => convertTimeCode(value)"
        :disabled="!(isAdmin || roomSettings.userControl)"
        @change="seek"/>
    </b-field>
    <h2 class="subtitle is-6 time">{{convertTimeCode(roomStatus.player.timeCode)}} / {{convertTimeCode(roomStatus.player.timeLength)}}</h2>
  </div>
</template>

<script>
export default {
  name: 'Player',
  computed: {
    isAdmin () {
      return this.$store.state.room.admin
    },
    roomStatus () {
      return this.$store.state.room.roomStatus
    },
    roomSettings () {
      return this.$store.state.room.roomSettings
    },
    localSettings () {
      return this.$store.state.room.localSettings
    },
    player () {
      return this.$refs.youtube.player
    },
    playerVars () {
      const adminVars = {
        autoplay: 1,
        controls: 0,
        disablekb: 0,
        modestbranding: 1,
        rel: 0
      }
      const userVars = {
        autoplay: 1,
        controls: 0,
        disablekb: 1,
        modestbranding: 1,
        rel: 0
      }
      return this.isAdmin ? adminVars : userVars
    },
    lastUserCommand () {
      return this.$store.state.room.lastUserCommand
    }
  },
  mounted () {
    this.player.addEventListener('onStateChange', this.playerStateChange)
    setInterval(this.updateTimeCode, 1000)
  },
  watch: {
    roomStatus: function (status) {
      if (!this.localSettings.playLink) {
        this.player.pauseVideo()
        return
      }

      this.player.seekTo(status.player.timeCode, true)
      if (status.player.playing) this.player.playVideo()
      else this.player.pauseVideo()
    },
    lastUserCommand: function (command) {
      switch (command.type) {
        case 'play':
          this.play()
          break
        case 'seek':
          this.seek(command.argument)
          break
        case 'skip':
          this.skip()
          break
      }
    }
  },
  methods: {
    async playerStateChange (event) {
      console.log('[PLAYER] Status change ' + event.data)

      if (this.isAdmin) {
        this.$store.dispatch('room/setCurrent', {
          playerStatus: event.data,
          timeCode: await this.player.getCurrentTime(),
          timeLength: await this.player.getDuration(),
          title: await event.target.getVideoData().title
        })
      } else {
        if (this.roomStatus.player.playing) this.player.playVideo()
        else this.player.pauseVideo()
      }
    },
    play () {
      if (this.isAdmin) {
        if (this.roomStatus.player.playing) this.player.pauseVideo()
        else this.player.playVideo()
      } else if (this.roomSettings.userControl) {
        this.$store.dispatch('rtc/broadcast', { message: { type: 'play' }, type: 'userCommand' })
      }
    },
    async mute () {
      if (await this.player.isMuted()) this.player.unMute()
      else this.player.mute()
    },
    volume (volume) {
      this.player.setVolume(volume)
    },
    skip () {
      if (this.isAdmin) this.$store.commit('room/CURRENT_END')
      else if (this.roomSettings.userControl) this.$store.dispatch('rtc/broadcast', { message: { type: 'skip' }, type: 'userCommand' })
    },
    seek (time) {
      if (this.isAdmin) this.player.seekTo(time, true)
      else if (this.roomSettings.userControl) this.$store.dispatch('rtc/broadcast', { message: { type: 'seek', argument: time }, type: 'userCommand' })
    },
    async updateTimeCode () {
      if (this.localSettings.playLink) this.$store.dispatch('room/setTimeCode', await this.player.getCurrentTime())
    },
    convertTimeCode (timeCode) {
      var minutes = Math.round(timeCode / 60)
      var seconds = Math.round(timeCode % 60)
      if (minutes < 10) minutes = '0' + minutes
      if (seconds < 10) seconds = '0' + seconds
      return minutes + ':' + seconds
    }
  }
}
</script>

<style local>
.controls {
  text-align: center;
  max-width: 500px;
}

.playerButton {
  margin-left: 10px;
}

.playerVolume {
  margin-left: 30px;
  margin-right: 30px;
  max-width: 150px;
}

.player {
  text-align: center;
}

.time {
  text-align: center;
}
</style>
