<template>
<b-modal id="add-permission-modal" title="Add permission" @shown="afterShow" ok-title="Add" @ok="addPermission">
  <SearchUser ref="searchUser" @searchUserEnter="addPermission" />
</b-modal>
</template>

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

export default {
  name: 'AddPermissionModal',
  components: {
    SearchUser
  },
  methods: {
    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;

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

      client.addPermission(userId, permission, this.$store.state.input)
        .then(res => {
          this.$store.commit('updatePermissionsPanel', res);
          this.$bvModal.hide('add-permission-modal');
        });
    }
  }
};
</script>
