<template>
  <div class="divMaster row ">
    <div class="col-10 offset-1 d-flex flex-wrap justify-content-center mb-5">
      <div
        class="card m-3"
        style="width: 12rem;"
        v-bind:key="libro.id"
        v-for="libro in Libros"
        @click="descripcion(libro.id)"
      >
        <router-link :to="{ path: 'home' }" class="textt">
          <img :src="libro.img" class="card-img-top rounded" alt="libro" />
          <div class="card-body cd textt">
            <p class="card-text textt">
              {{ libro.title }}
            </p>
          </div>
        </router-link>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import config from "../config/config.js";
export default {
  components: {},

  data() {
    return {
      categoria: "",
      Libros: []
    };
  },
  methods: {
    async descripcion(idLibro) {
      localStorage.clear();
      window.localStorage.setItem("idLibro", idLibro);
      this.$router.push("/desc");
    }
  },
  async created() {
    let path = `${config.api}`;
    this.categoria = window.localStorage.getItem("categoria");
    try {
      let similares = await axios.get(
        `${config.api}/temaLibro?categoria=${this.categoria}`
      );
      similares = similares.data.data;
      console.log(` este es el resutlado${similares}`);
      for (let i = 0; i < similares.length; i++) {
        let config = {
          // example url
          url: `${path}/libroImagen?idLibro=${similares[i].idLibro}`,
          method: "GET",
          responseType: "blob"
        };
        try {
          await axios(config).then(response => {
            let reader = new FileReader();
            reader.readAsDataURL(response.data);
            reader.onload = () => {
              this.Libros.push({
                id: similares[i].idLibro,
                title: similares[i].titulo,
                img: reader.result
              });
              //this.Libros[i].img = reader.result;
            };
          });
        } catch (error) {
          console.log(`Ocurrio un error con la imagen desc: ${error}`);
        }
      }
    } catch (error) {
      console.log(`Ocurrio un error ${error}`);
    }
  },
  beforeCreate() {
    if (!window.localStorage.getItem("categoria")) this.$router.push("/");
    else this.categoria = window.localStorage.getItem("categoria");
  }
};
</script>

<style scoped>
.divMaster {
  height: auto;
}
.card {
  border: none !important;
  border-bottom: 5px solid #1b3d70 !important;
}
a {
  text-decoration: none !important;
  color: black;
}
</style>
