<template>
  <b-tab title="Members">
    <div v-if="model.membersPanel !== null">
      <b-list-group v-for="member in model.membersPanel.items" id="members-list">
        <b-list-group-item href="#">
          <div class="float-left">
            <User v-bind:user="member" />
          </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>
    </div>
    <div class="text-center" v-if="model.membersPanel !== null">
      <b-pagination
        v-model="model.membersPanel.page"
        :total-rows="model.membersPanel.totalItems"
        :per-page="model.membersPanel.pageSize"
        aria-controls="members-list"
        align="center"
        v-on:change="setPage"
      ></b-pagination>
    </div>
    <ConfirmRemoveMemberModal ref="confirmRemoveMemberModal" />
  </b-tab>
</template>

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

export default {
  name: 'MembersPanel',
  components: {
    User,
    ConfirmRemoveMemberModal
  },
  computed: mapState({
    model: state => state.model
  }),
  methods: {
    openRemoveMemberModal: function(member) {
      getMemberPermission(this, member)
        .then(memberPermission => {
          this.$refs.confirmRemoveMemberModal.openRemoveMemberModal(member, memberPermission);
        });
    },
    setPage: function(page) {
      console.log('setPage ', page);
    }
  }
}

function getMemberPermission(self, member) {
  return new Promise((resolve, reject) => {
    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>
