<template>
<b-modal id="add-group-modal" title="Add group" @show="resetModal" @shown="afterShow" ok-title="Add" @ok="addGroup">
  <b-form inline>
    <label class="w-25" for="new-group-name-input">Group name:</label>
    <b-form-input v-model="newGroupName" id="new-group-name-input" ref="newGroupNameInput" class="w-75" aria-describedby="new-group-name-input-feedback" :state="newGroupNameState" v-on:input="resetError" @keydown.native.enter="addGroup">
    </b-form-input>
    <b-form-invalid-feedback id="new-group-name-input-feedback" class="text-right">{{newGroupNameError}}</b-form-invalid-feedback>
    <b-form-checkbox class="mt-3 ml-3" v-model="allowChildGroups">allow child groups</b-form-checkbox>
  </b-form>
</b-modal>
</template>

<script>
import client from 'api-client';

export default {
  name: 'AddGroupModal',
  computed: {
    newGroupNameState() {
      if (this.newGroupNameError) {
        return false;
      }
      return null;
    }
  },
  data: function() {
    return {
      newGroupName: '',
      newGroupNameError: '',
      allowChildGroups: false
    };
  },
  methods: {
    resetModal: function() {
      this.newGroupName = null;
      this.allowChildGroups = false;
      this.resetError();
    },
    afterShow: function() {
      this.$refs.newGroupNameInput.focus();
    },
    resetError: function() {
      this.newGroupNameError = null;
    },
    addGroup: function(event) {
      // Prevent modal from closing
      event.preventDefault();

      if (!this.newGroupName) {
        this.newGroupNameError = "Group name is required";
      } else {
        client.addGroup(this.newGroupName, !this.allowChildGroups, this.$store.state.input)
          .then(res => {
            this.$store.commit('updateGroupsPanel', res);
            this.$bvModal.hide('add-group-modal');
          })
          .catch(res => {
            this.newGroupNameError = res.message;
          });
      }
    }
  }
}
</script>
