<template>
<b-tab title="Members" :title-link-class="{ 'd-none': (model.permission === 'TRAVERSE') }">
  <div v-if="model.membersPanel !== null">
    <b-list-group v-for="member in model.membersPanel.items" id="members-list" v-bind:key="member.memberId">
      <b-list-group-item href="#" @click.prevent="openUser(member)">
        <div class="float-left">
          <User :user="member" :anchor="false" />
        </div>
        <span v-if="model.permission === 'ADMIN' || model.permission === 'MANAGE_MEMBERS'" class="float-right">
          <a href="#" v-on:click.stop="openRemoveMemberModal(member)" class="text-danger" title="Remove member">
            <font-awesome-icon icon="trash"></font-awesome-icon>
          </a>
        </span>
      </b-list-group-item>
    </b-list-group>
    <p v-if="model.membersPanel.items.length === 0">No direct members</p>
  </div>
  <Paginator :paginatedPanel="model.membersPanel" :onUpdate="updatePagination" :paginatorInput="input" />
  <ConfirmRemoveMemberModal ref="confirmRemoveMemberModal" />
</b-tab>
</template>

<script>
import client from 'api-client';
import User from './User.vue';
import Paginator from './Paginator.vue';
import ConfirmRemoveMemberModal from './modals/ConfirmRemoveMemberModal.vue';
import { mapState } from 'vuex';

export default {
  name: 'MembersPanel',
  components: {
    User,
    ConfirmRemoveMemberModal,
    Paginator
  },
  computed: mapState({
    model: state => state.model,
    input: state => state.input
  }),
  methods: {
    openRemoveMemberModal: function(member) {
      getMemberPermission(this, member)
        .then(memberPermission => {
          this.$refs.confirmRemoveMemberModal.openRemoveMemberModal(member, memberPermission);
        });
    },
    updatePagination: function() {
      client.fetchMembersPanel(this.input)
        .then(panel => {
          this.$store.commit('updateMembersPanel', panel);
        });
    },
    openUser(member) {
      this.$router.push({ path: `/user/${member.id}` }, () => {});
    }
  }
}

function getMemberPermission(self, member) {
  return new Promise((resolve) => {
    if (self.model.permission === 'ADMIN') {
      let groupId = self.$store.state.input.selectedGroupId;
      client.getPermission(groupId, member.id)
        .then(res => {
          resolve(res.permission);
        });
    } else {
      resolve(null);
    }
  });
}
</script>
