<template>
  <div class="search container">
    <div class="columns">
      <div class="column">
        <h1 class="title is-6 filterTitle">Filtres</h1>
        <Filters v-bind:tags="tags" v-on:setTags="refreshResults"/>
      </div>
      <div v-if="result" class="column is-four-fifths">
        <h1 class="title is-6">{{result.total}} résultats - page {{result.page}}</h1>
        <div v-for="model in result.models" v-bind:key="model.name">
          <ModelCard v-bind:model="model"/>
        </div>
        <b-pagination :total="result.total" :current.sync="result.page" :per-page="resultSize" @change="changePage"/>
      </div>
      <div v-else class="column is-four-fifths">
        <h1 class="title">no modelo</h1>
      </div>
    </div>
    <b-loading :active.sync="isLoading" :is-full-page="false"/>
  </div>
</template>

<script>
import Filters from '@/components/Filters.vue'
import ModelCard from '@/components/ModelCard.vue'

export default {
  name: 'Search',
  components: {
    Filters,
    ModelCard
  },
  data () {
    return {
      tags: '',
      result: true,
      paramTags: '',
      paramSearch: '',
      paramPerf: '',
      resultSize: 10,
      page: 1,
      isLoading: true
    }
  },
  async mounted () {
    this.tags = await this.getTags()
    this.result = await this.getResult()
    this.isLoading = false
  },
  methods: {
    async changePage (page) {
      this.page = page
      this.result = await this.getResult()
    },
    async setTags (tags, perfValue) {
      this.paramTags = tags
      this.paramPerf = perfValue
      this.result = await this.getResult()
    },
    async getTags () {
      const url = this.$serverurl + 'tags'
      const response = await fetch(url)
      try {
        return await response.json()
      } catch (error) {
        return null
      }
    },
    async getResult () {
      const url = new URL(this.$serverurl + 'search')
      const params = new URLSearchParams()
      const nameParam = this.$route.query.n

      if (nameParam != null) params.append('q', nameParam)
      if (this.paramTags != null) params.append('tag', this.paramTags)
      if (this.paramPerf != null) params.append('perf', this.paramPerf)

      params.append('size', this.resultSize)
      params.append('page', this.page)

      console.log('get models ' + nameParam + ' + ' + this.paramPerf + ' + ' + this.paramTags)

      url.search = params
      const response = await fetch(url)
      try {
        return await response.json()
      } catch (error) {
        return null
      }
    }
  }
}
</script>

<style scoped>
.search {
  padding-top: 50px;
}

.filterTitle {
  margin-left: 15px;
}
</style>