<template>
<b-modal id="rename-group-modal" title="Rename group" ok-title="Rename" @ok="renameGroup">
  <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" class="text-right">{{newGroupNameError}}</b-form-invalid-feedback>
    <b-form-checkbox class="mt-3 ml-3" v-model="leaf">is leaf</b-form-checkbox>
  </b-form>
</b-modal>
</template>

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

export default {
  name: 'RenameGroupModal',
  computed: {
    newGroupNameState() {
      if (this.newGroupNameError) {
        return false;
      }
      return null;
    }
  },
  data: function() {
    return {
      groupId: '',
      oldGroupName: '',
      newGroupName: '',
      newGroupNameError: '',
      leaf: false
    };
  },
  methods: {
    resetError: function() {
      this.newGroupNameError = null;
    },
    openRenameGroupModal: function(group) {
      this.newGroupName = group.groupName;
      this.groupId = group.groupId;
      this.leaf = group.leaf;
      this.$bvModal.show('rename-group-modal');
    },
    renameGroup: function(event) {
      // Prevent modal from closing
      event.preventDefault();

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

      if (this.oldGroupName === this.newGroupName) {
        this.$bvModal.hide('rename-group-modal');
        return;
      }

      client.renameGroup(this.groupId, this.newGroupName, this.leaf, this.$store.state.input)
        .then(res => {
          if (res.status === 400) {
            this.newGroupNameError = res.message;
          } else {
            this.$store.commit('updateGroupsPanel', res);
            this.$bvModal.hide('rename-group-modal');
          }
        });
    }
  }
}
</script>
