<template>
  <div>
    <v-row>
      <v-col cols="3">
        <v-select
          v-model="category"
          :items="categories"
          label="Catégorie"
          solo
        ></v-select>
      </v-col>
      <v-col cols="9" class="text-end">
        <v-btn-toggle v-show="search.length === 0">
          <v-btn v-if="page != 1" @click="page--">Préc.</v-btn>
          <v-btn @click="page = 1">{{ page }} / {{ nbPages }}</v-btn>
          <v-btn v-if="page != nbPages" @click="page++">Suiv.</v-btn>
        </v-btn-toggle>
      </v-col>
    </v-row>
    <v-row justify="center">
      <v-card
        class="ma-2"
        v-for="(product, index) in products"
        :key="index"
        max-width="270"
      >
        <v-img height="270" :src="apiUri + product.photo.url"></v-img>
        <v-card-title>{{ product.name }}</v-card-title>
        <v-card-text>
          <strong>{{ product.unit_price }} €</strong>
        </v-card-text>
      </v-card>
  </v-row>
  </div>
</template>

<script>
import CategoriesQuery from "../graphql/getCategories.gql";
import ProductsQuery from "../graphql/getProducts.gql";
import ProductsByCategoryQuery from "../graphql/getProductsByCategory.gql";
import ProductsBySearchQuery from "../graphql/getProductsBySearch.gql";
import ProductsByCategoryAndSearchQuery from "../graphql/getProductsByCategoryAndSearch.gql";

export default {
  name: "ProductList",
  props: {
    search: {
      type: String,
      default: ""
    }
  },
  created() {
    this.$on("queryError", error => {
      throw new Error("Erreur : "+error.message);
    })
  },
  data: () => ({
    apiUri: process.env.VUE_APP_STRAPI_API,
    products: [],
    categories: [],
    category: 0,
    start: 0,
    page: 1,
    perPage: 10
  }),
  computed: {
    nbPages() {
      if (this.categories.length > 0) {
        const selectedCategory = this.categories.filter(category => {
          return category.value === this.category
        });
        return Math.ceil(selectedCategory[0].nbProducts / this.perPage);
      }

      return "...";
    },
  },
  watch: {
    page(newVal) {
      this.start = (newVal - 1) * this.perPage;
    },
  },
  apollo: {
    // options par défaut pour toutes les requêtes
    $query: {
      fetchPolicy: "cache-and-network"
    },
    products: {
      query() {
        if (this.category && this.search.length > 0) {
          return ProductsByCategoryAndSearchQuery;
        } else if (this.category) {
          return ProductsByCategoryQuery;
        } else if (this.search.length > 0) {
          return ProductsBySearchQuery;
        } else {
          return ProductsQuery;
        }
      },
      variables() {
        return {
          start: this.start,
          limit: this.perPage,
          category: ~~this.category, // parse to int
          search: this.search
        }
      },
      debounce: 250,
      error(error, vm) {
        vm.$emit("queryError", error);
      }
    },
    categories: {
      query: CategoriesQuery,
      update (data) {
        console.log(data);
        const categories = [{
          text: "Toutes catégories",
          value: 0,
          nbProducts: data.productsConnection.aggregate.totalCount
        }];

        data.categories.forEach((category, index) => {
          categories.push({ 
            text: category.name,
            value: category.id,
            nbProducts: data.productsConnection.groupBy.category[index].connection.aggregate.count
          });
        });

        return categories;
      },
      error(error, vm) {
        vm.$emit('queryError', error);
      }
    }
  }
}
</script>