<template>
  <b-container>
    <b-row>
      <b-col>
        <h1>Collection: {{ collectionName }}</h1>
      </b-col>
    </b-row>
    <big-chungus-loader text="Fetching track list..." v-if="processing"/>
    <b-row v-else>
      <b-col class="my-4">

        <b-table :items="tracklist" :fields="fields" hover borderless @row-clicked="rowClicked"
                 tbody-tr-class="clickable-table-row-thing">
          <template #cell(cover_url)="data">
            <b-img-lazy :src="data.item.cover_url_small" height="45px" blank-src="@/assets/music_placeholder.png"
                        v-if="!!data.item.cover_url_small"/>
            <b-img src="@/assets/music_placeholder.png" height="45px" v-else/>
          </template>

          <template #cell(id)="data">
            <div class="text-right">
              <b-button variant="success" :disabled="!data.item.spotify_id" @click="startPlayer(data.item.spotify_id)">
                Play
              </b-button>
            </div>
          </template>
        </b-table>

      </b-col>
    </b-row>
  </b-container>
</template>

<script>
import BigChungusLoader from "@/components/BigChungusLoader";

export default {
  name: "Collection",
  components: {
    BigChungusLoader
  },
  data() {
    return {
      processing: true,
      collectionName: "",
      totalTracks: 0,
      fields: [
        {
          key: "cover_url",
          label: "Cover"
        },
        "artist",
        "album",
        "title",
        {
          key: "id",
          label: ""
        }
      ],
      tracklist: []
    }
  },
  methods: {
    rowClicked(data) {
      this.$router.push({name: 'Item', params: {id: data.id}});
    },
    startPlayer(spotify_id) {
      this.$store.dispatch('openPlayer', spotify_id);
    }
  },
  mounted() {
    this.$api.getList(this.$route.params.id).then((data) => {
      if (data) {
        this.tracklist = data.itemlist;
        this.collectionName = data.name;
        this.totalTracks = data.element_count;
        this.processing = false;
      } else {
        this.$showToast("Invalid response from server");
      }
    }).catch(({text}) => {
      this.$showToast(text);
    });
  }
}
</script>

<style>
/* Should be scoped, but that could not change row style*/
.clickable-table-row-thing {
  cursor: pointer;
}
</style>