<template>
<b-modal id="add-permission-modal" title="Add permission" @show="beforeShow" @shown="afterShow" :ok-title="okTitle" @ok="addPermission" :ok-variant="okBtnVariant" size="lg">
  <SearchUser ref="searchUser" @searchUserEnter="addPermission" />
  <b-alert :show="!!existingPermission" variant="warning" class="mt-3">
    <strong>Warning</strong>: the user has already a permission ({{existingPermission}}). Click confirm to override it.
  </b-alert>
</b-modal>
</template>

<script>
import client from 'api-client';
import SearchUser from './SearchUser.vue'

export default {
  name: 'AddPermissionModal',
  components: {
    SearchUser
  },
  computed: {
    okBtnVariant: function() {
      return this.existingPermission ? 'danger' : 'primary';
    },
    okTitle: function() {
      return this.existingPermission ? 'Confirm' : 'Add';
    }
  },
  data() {
    return {
      existingPermission: null
    };
  },
  methods: {
    beforeShow() {
      this.existingPermission = null;
    },
    afterShow: function() {
      this.$refs.searchUser.$refs.userInput.focus();
    },
    addPermission: function(event) {
      // Prevent modal from closing
      if (event) {
        event.preventDefault();
      }

      let userId = this.$refs.searchUser.selectedUser;
      let permission = this.$refs.searchUser.permission;
      let input = this.$store.state.input;

      if (!userId || !permission) {
        return;
      }

      client.getPermission(input.selectedGroupId, userId)
        .then(res => {
          if (res.permission && res.permission !== permission && !this.existingPermission) {
            this.existingPermission = res.permission;
          } else {
            client.addPermission(userId, permission, input, !!this.existingPermission)
              .then(res => {
                this.$store.commit('updatePermissionsPanel', res);
                this.$bvModal.hide('add-permission-modal');
              });
          }
        });
    }
  }
};
</script>
