<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 http from "@/api/http";
import { debounce } from "lodash-es";

export default {
  name: "ProductList",
  async created() {
    this.products = await this.getProducts(0);
    const categories = await this.getCategories();
    const total = await this.getProductsCount();
    this.initCategories(categories, total);
    this.getProductsDebounced = debounce(async function(start) {
      this.products = await this.getProducts(start);
    }, 300)
  },
  props: {
    search: {
      type: String,
      default: ""
    }
  },
  data: () => ({
      apiUri: process.env.VUE_APP_STRAPI_API,
      products: [],
      categories: [],
      category: 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: {
    async page(newVal) {
      const start = (newVal - 1) * this.perPage;
      this.products = await this.getProducts(start);
    },
    async category() {
      this.products = await this.getProducts(0);
    },
    async search() {
      this.getProductsDebounced(0);
    }
  },
  methods: {
    async getProducts(start) {
      let uri = `/products?_start=${start}&_limit=${this.perPage}`;
      
      if (this.category) {
        uri += "&category=" + this.category;
      }

      if (this.search.length > 0) {
        uri += "&name_contains=" + this.search;
      }

      return await http.callURI(uri);
    },
    async getProductsCount() {
      return await http.callURI(`/products/count`);
    },
    async getCategories() {
      return await http.callURI(`/categories`);
    },
    initCategories(categories, totalProducts) {
      this.categories.push({
        text: "Toutes catégories",
        value: 0,
        nbProducts: totalProducts
      });
      categories.forEach(categorie => {
        this.categories.push({ 
          text: categorie.name,
          value: categorie.id,
          nbProducts: categorie.products.length
        });
      });
    }
  }
}
</script>