<template>
  <div>
    <b-button icon-left="plus" @click="addLinkPrompt">Add link</b-button>
    <b-table :data="roomStatus.playlist" striped hoverable default-sort="vote">
      <template slot-scope="props">
        <b-table-column field="title" label="Title">
          {{props.row.title}}
        </b-table-column>

        <b-table-column field="link" label="Link">
          {{props.row.link}}
        </b-table-column>

        <b-table-column field="vote" label="Votes">
          {{props.row.votes}}
        </b-table-column>

        <b-table-column field="voters" label="Voters" :visible="isAdmin">
          {{props.row.voters}}
        </b-table-column>

        <b-table-column>
          <b-button v-if="hasVoted(props.row)" icon-left="arrow-down-bold-outline" type="is-dark" @click="vote (props.row.link, props.row.linkID, false)"/>
          <b-button v-else icon-left="arrow-up-bold-outline" type="is-dark" @click="vote (props.row.link, props.row.linkID, true)"/>
        </b-table-column>
      </template>
    </b-table>
  </div>
</template>

<script>
export default {
  name: 'Palylist',
  computed: {
    isAdmin () {
      return this.$store.state.room.admin
    },
    roomStatus () {
      return this.$store.state.room.roomStatus
    }
  },
  methods: {
    addLinkPrompt () {
      this.$buefy.dialog.prompt({
        message: 'Add a youtube link',
        trapFocus: true,
        inputAttrs: {
          placeholder: 'https://www.youtube.com/watch?v=YItIK09bpKk',
          minlength: 10
        },
        cancelText: 'Nah',
        confirmText: 'Add',
        onConfirm: (link) => this.addLink(link)
      })
    },
    addLink (link) {
      const linkID = this.$youtube.getIdFromUrl(link)
      if (linkID === null) {
        this.$buefy.toast.open('Invalid youtube link')
        return
      }
      this.vote(link, linkID, true)
    },
    vote (link, linkID, isPositive) {
      if (this.isAdmin) {
        this.$store.dispatch('room/vote', { link: link, linkID: linkID, isPositive: isPositive, voterName: this.$store.state.rtc.name })
      } else {
        this.sendVote(link, linkID, isPositive)
      }
    },
    sendVote (link, linkID, isPositive) {
      const message = {
        type: 'vote',
        link: link,
        linkID: linkID,
        isPositive: isPositive,
        voterName: this.$store.state.rtc.name
      }
      this.$store.dispatch('rtc/broadcast', { message: message, type: 'vote' })
    },
    hasVoted (play) {
      return play.voters.includes(this.$store.state.rtc.name)
    }
  }
}
</script>
