<script setup>
  import { computed } from 'vue'
  import { getBook, getImagePathOrDefault, putReadBook, putWantReadBook, putRateBook } from './api.js'
  import { onBeforeRouteUpdate } from 'vue-router'
  import { VRating } from 'vuetify/components/VRating';
  import BigIcon from './BigIcon.vue';

  const props = defineProps({
  id: String
});

  let { data, error } = getBook(props.id);
  const imagePathOrDefault = computed(() => getImagePathOrDefault(data.value.coverPath));
  onBeforeRouteUpdate(async (to, from) => {
    let res = getBook(to.params.id);
    data = res.data;
    error = res.error;
  })

  function onRatingUpdate(rating) {
    data.value.rating = rating * 2;
    putRateBook(props.id, {rating: data.value.rating});
  }

  function onReadIconClick() {
    data.value.read = !data.value.read;
    if (data.value.read) {
      data.value.wantread = false;
    }
    putReadBook(props.id, {read: data.value.read});
  }

  function onWantReadIconClick() {
    data.value.wantread = !data.value.wantread;
    putWantReadBook(props.id, {wantread: data.value.wantread});
  }

</script>

<template>
  <div v-if="error">{{$t('bookform.error', {error: error.message})}}</div>
  <div v-if="data" class="columns">
    <div class="column is-narrow ml-6">
      <figure class="image">
        <img v-bind:src="imagePathOrDefault" v-bind:alt="data.title">
      </figure>
      <VRating
          half-increments
          hover
          :length="5"
          size="x-large"
          density="compact"
          :model-value="data.rating/2"
          @update:modelValue="onRatingUpdate"
          active-color="bulma-body-color"
          class="centered"
          />
    </div>
    <div class="column">
      <h3 class="title">{{data.title}}</h3>
      <h3 class="subtitle">{{data.author}}</h3>
      <p>{{data.summary}}</p>
    </div>
    <div class="column">
      <div class="iconscontainer">
        <BigIcon icon="BIconEye"
                 :legend="$t('bookform.wantread')"
                 :isSet="data.wantread"
                 @click="onWantReadIconClick"/>
        <BigIcon icon="BIconBook"
                 :legend="$t('bookform.startread')"
                 :isSet="false"/>
        <BigIcon icon="BIconCheckCircle"
                 :legend="$t('bookform.read')"
                 :isSet="data.read"
                 @click="onReadIconClick"/>
      </div>
    </div>
  </div>
</template>

<style scoped>
img {
  max-height:500px;
  max-width:500px;
  height:auto;
  width:auto;
}

.centered {
  display:flex;
  justify-content:center;
  align-items:center;
}

.iconscontainer {
  border: solid;
  border-radius: 50px;
  width: 250px;
}


</style>
