<template>
  <div>
    <GroupsBreadcrumb />
    <b-card no-body>
      <b-tabs content-class="mt-3" card v-on:input="tabChanged">
        <GroupsPanel />
        <MembersPanel />
        <PermissionsPanel />
        <template slot="tabs-end">
          <b-button variant="primary" class="in-tabs-header-btn" v-if="showAddGroupBtn" v-on:click="openAddGroupModal">Add group</b-button>
          <b-button variant="primary" class="in-tabs-header-btn" v-if="showAddMemberBtn" v-on:click="openAddMemberModal">Add member</b-button>
          <b-button variant="primary" class="in-tabs-header-btn" v-if="showAddCollaboratorBtn" v-on:click="openAddMemberModal">Add collaborator</b-button>
          <b-button variant="primary" class="in-tabs-header-btn" v-if="showAddPermissionBtn" v-on:click="openAddPermissionModal">Add permission</b-button>
        </template>
      </b-tabs>
    </b-card>
    <AddGroupModal />
    <AddMemberModal />
    <AddPermissionModal />
  </div>
</template>

<script>
import GroupsBreadcrumb from './GroupsBreadcrumb.vue'
import GroupsPanel from './GroupsPanel.vue'
import MembersPanel from './MembersPanel.vue'
import PermissionsPanel from './PermissionsPanel.vue'
import AddGroupModal from './modals/AddGroupModal.vue'
import AddMemberModal from './modals/AddMemberModal.vue'
import AddPermissionModal from './modals/AddPermissionModal.vue'
import { mapState } from 'vuex';

export default {
  name: 'Main',
  components: {
    GroupsBreadcrumb,
    GroupsPanel,
    MembersPanel,
    PermissionsPanel,
    AddGroupModal,
    AddMemberModal,
    AddPermissionModal
  },
  computed: mapState({
    model: state => state.model,
    showAddMemberBtn: state => state.model.permission === 'ADMIN' && state.input.selectedTab === 'members',
    showAddCollaboratorBtn: state => state.model.permission === 'MANAGE_MEMBERS' && state.input.selectedTab === 'members',
    showAddGroupBtn: state => state.model.permission === 'ADMIN' && state.input.selectedTab === 'groups',
    showAddPermissionBtn: state => state.model.permission === 'ADMIN' && state.input.selectedTab === 'permissions'
  }),
  methods: {
    tabChanged: function(tabIndex) {
      let tab;
      switch(tabIndex) {
        case 0:
          tab = 'groups';
          break;
        case 1:
          tab = 'members';
          break;
        case 2:
          tab = 'permissions';
          break;
      }
      if(this.$store.state.input.selectedTab !== tab) {
        this.$store.state.input.selectedTab = tab;
        this.$store.commit('fetchGroupsModel');
      }
    },
    openAddGroupModal: function() {
      this.$bvModal.show('add-group-modal');
    },
    openAddMemberModal: function() {
      this.$bvModal.show('add-member-modal');
    },
    openAddPermissionModal: function() {
      this.$bvModal.show('add-permission-modal');
    }
  }
}
</script>

<style scoped>
  .in-tabs-header-btn {
    position: absolute;
    right: 8px;
    top: 8px;
  }
</style>
