<template>
  <b-modal id="add-group-modal" title="Add group" @show="resetModal" 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"
                    class="w-75"
                    aria-describedby="new-group-name-input-feedback"
                   :state="newGroupNameState"
                    v-on:input="resetError">
      </b-form-input>
      <b-form-invalid-feedback id="new-group-name-input-feedback">{{newGroupNameError}}</b-form-invalid-feedback>
    </b-form>
  </b-modal>
</template>

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

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

      if(!this.newGroupName) {
        this.newGroupNameError = "Group name is required";
        return;
      }

      let parent = this.$store.getters.selectedGroupId;
      client.addGroup(this.newGroupName, this.$store.state.input)
        .then(res => {
          if(res.status === 400) {
            this.newGroupNameError = res.message;
          } else {
            this.$store.commit('updateGroupsPanel', res);
            this.$bvModal.hide('add-group-modal');
          }
        });
    }
  }
}
</script>
