<template>
<b-tab title="Groups" active>
  <b-row>
    <b-col xs="12">
      <b-form-input placeholder="Search group" v-model="input.searchFilter" v-on:input="filterGroups"></b-form-input>
    </b-col>
  </b-row>
  <div id="groups-list" v-if="model.groupsPanel !== null">
    <b-list-group v-for="group in model.groupsPanel.items">
      <b-list-group-item href="#" v-on:click="openGroup(group)">
        <span class="float-left">{{group.groupName}}</span>
        <span v-if="group.permission === 'ADMIN'" class="float-right">
          <a href="#" v-on:click.stop="openRenameGroupModal(group)" title="Rename">
            <font-awesome-icon icon="edit"></font-awesome-icon>
          </a>
          &nbsp;
          <a href="#" v-on:click.stop="openRemoveGroupModal(group)" class="text-danger" title="Delete">
            <font-awesome-icon icon="trash"></font-awesome-icon>
          </a>
        </span>
      </b-list-group-item>
    </b-list-group>
    <p v-if="model.groupsPanel.items.length === 0">No groups</p>
  </div>
  <Paginator :paginatedPanel="model.groupsPanel" :onUpdate="updatePagination" />
  <RenameGroupModal ref="renameGroupModal" />
  <ConfirmRemoveGroupModal ref="confirmRemoveGroupModal" />
</b-tab>
</template>

<script>
import RenameGroupModal from './modals/RenameGroupModal.vue';
import ConfirmRemoveGroupModal from './modals/ConfirmRemoveGroupModal.vue';
import Paginator from './Paginator.vue';
import {
  mapState,
  mapActions
} from 'vuex';
import client from 'api-client';
import debounce from 'debounce'; // for delaying the input event (search filter)

export default {
  name: 'GroupsPanel',
  components: {
    RenameGroupModal,
    ConfirmRemoveGroupModal,
    Paginator
  },
  computed: mapState({
    model: state => state.model,
    input: state => state.input
  }),
  data: function() {
    return {
      groupFilter: ''
    };
  },
  methods: {
    openGroup: function(group) {
      this.$store.state.input.selectedGroupId = group.groupId;
      this.$store.state.input.searchFilter = null;
      client.fetchGroupsTab(this.input)
        .then(model => {
          this.$store.commit('updateGroups', model);
        });
    },
    openRenameGroupModal: function(group) {
      this.$refs.renameGroupModal.openRenameGroupModal(group);
    },
    openRemoveGroupModal: function(group) {
      this.$refs.confirmRemoveGroupModal.openRemoveGroupModal(group);
    },
    filterGroups: function() {
      client.fetchGroupsPanel(this.input)
        .then(panel => {
          this.$store.commit('updateGroupsPanel', panel);
        });
    },
    updatePagination: function() {
      client.fetchGroupsPanel(this.input)
        .then(panel => {
          this.$store.commit('updateGroupsPanel', panel);
        });
    }
  },
  created: function() {
    this.filterGroups = debounce(this.filterGroups, 500)
  }
}
</script>

<style scoped>
#groups-list {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
