<template>
<div class="mt-sm-3">
  <div>
    <p>Search results:</p>
    <b-list-group v-for="item in model.genericSearchResults.items" v-bind:key="item.id">
      <b-list-group-item href="#" v-on:click="openSearchResult(item)">
        <span class="float-left">
          <font-awesome-icon icon="folder" v-if="item.type === 'GROUP'"></font-awesome-icon>
          <font-awesome-icon icon="user" v-if="item.type === 'USER'"></font-awesome-icon>
          {{item.label}}
        </span>
      </b-list-group-item>
    </b-list-group>
    <Paginator :paginatedPanel="model.genericSearchResults" :onUpdate="updateSearchResults" :paginatorInput="input.genericSearch" />
  </div>
</div>
</template>

<script>
import Paginator from './Paginator.vue';
import { mapState } from 'vuex';

export default {
  name: 'GenericSearchResults',
  components: {
    Paginator
  },
  computed: mapState({
    model: state => state.model,
    input: state => state.input
  }),
  created () {
    this.updateSearchResults();
  },
  watch: {
    // call again the method if the route changes
    '$route': 'updateSearchResults'
  },
  methods: {
    openSearchResult: function(result) {
      switch (result.type) {
        case 'GROUP':
          this.$store.dispatch('openGroup', result.id);
          break;
        case 'USER':
          this.$router.push({ path: `/user/${result.id}` }, () => {});
          break;
      }
    },
    updateSearchResults: function() {
      this.$store.dispatch('search', this.$route.query.q);
    }
  }
}
</script>
