<template>
  <b-container>
    <b-row>
      <b-col>
        <h1>
          <b-button variant="transparent" class="m-1" :to="{name: 'Collection', params: {id: $route.query.collection}, query: {p: $route.query.srcpage}}">
            <b-icon icon="arrow-left-circle-fill"/>
          </b-button>
          {{ songInfo.type | capitalize }}
        </h1>
      </b-col>
    </b-row>
    <big-chungus-loader text="Fetching item info..." v-if="processing"/>
    <b-row v-else>
      <b-col class="my-4">
        <div>
          <expandable-image :src="songInfo.cover_url" id="cover-art" :text="coverArtTitle"/>
        </div>
        <div class="my-3">
          <p><b>Artist:</b> {{ songInfo.artist }} </p>
          <hr class="info-separator">
          <p><b>Album:</b> {{ songInfo.album }}</p>
          <hr class="info-separator">
          <p><b>Title:</b> {{ songInfo.title }}</p>
        </div>
        <div class="my-3">
          <b-button :disabled="!songInfo.spotify_id" :href="spotifyLink" target="_blank">Open on Spotify!</b-button>&nbsp;
          <b-button variant="success" :disabled="!songInfo.spotify_id" @click="startPlayer"><b-icon icon="play-fill"/>  Play</b-button>

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

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

export default {
  name: "Item",
  components: {
    BigChungusLoader,
    ExpandableImage
  },
  data() {
    return {
      processing: true,
      songInfo: {}
    }
  },
  mounted() {
    this.$api.getItem(this.$route.params.id).then((data) => {
      if (data) {
        this.songInfo = data;
        this.processing = false;
      } else {
        this.$showToast("Invalid response from server");
      }
    }).catch(({text}) => {
      this.$showToast(text);
    });
  },
  methods: {
    startPlayer() {
      this.$store.dispatch('openPlayer', this.songInfo.spotify_id);
    }
  },
  computed: {
    spotifyLink() {
      if (this.songInfo.spotify_id) {
        const id_parts = this.songInfo.spotify_id.split(":");
        return `https://open.spotify.com/${id_parts[1]}/${id_parts[2]}`;
      } else {
        return "";
      }
    },
    coverArtTitle() {
      // TODO: do better
      if (this.songInfo.artist && this.songInfo.album ) {
        return this.songInfo.artist + ' - ' + this.songInfo.album;
      }
      return this.songInfo.album || this.songInfo.artist || this.songInfo.title;
    }
  },
  filters: {
    capitalize(value) {
      if (!value) return ''
      value = value.toString()
      return value.charAt(0).toUpperCase() + value.slice(1)
    }
  }
}
</script>

<style scoped>
#cover-art {
  max-width: 100%;
  width: 25vh;
}

hr.info-separator {
  width: 30vh;
  margin-left: 0;
}
</style>