<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 client from 'api-client';
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
  }),
  methods: {
    openSearchResult: function(result) {
      switch (result.type) {
        case 'GROUP':
          this.$store.commit('openGroup', result.id);
          break;
        case 'USER':
          client.openUserSearchResult(result.id)
            .then(model => {
              this.$store.commit('displayUserSearchResults', [result.label, model]);
            });
          break;
      }
    },
    updateSearchResults: function() {
      client.search(this.input)
        .then(results => {
          this.$store.commit('displaySearchResults', results);
        });
    }
  }
}
</script>
