<template>
<b-modal id="share-modal" :title="'Share ' + node.path" okTitle="Save" @show="onShow" @ok.prevent="share" size="lg">
  <h5>Read permissions</h5>
  <ShareInputGroup id="user-read" :values="userRead" :options="people" label="Users" placeholder="Search user..." buttonText="Add user" />
  <ShareInputGroup id="group-read" :values="groupRead" :options="groups" label="Groups" placeholder="Search group..." buttonText="Add group" />
  <h5 class="mt-3">Write permissions</h5>
  <ShareInputGroup id="user-write" :values="userWrite" :options="people" label="Users" placeholder="Search user..." buttonText="Add user" />
  <ShareInputGroup id="group-write" :values="groupWrite" :options="groups" label="Groups" placeholder="Search group..." buttonText="Add group" />
  <b-form-checkbox id="recursive" v-model="recursive" name="recursive">Apply also to children</b-form-checkbox>
</b-modal>
</template>

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

function setArray(array, newValues) {
  array.splice(0, array.length);
  for (let value of newValues) {
    array.push(value);
  }
}

export default {
  components: {
    ShareInputGroup
  },
  computed: {
    node() { return this.$store.state.nodeToShare; }
  },
  data() {
    return {
      groupRead: [],
      userRead: [],
      groupWrite: [],
      userWrite: [],
      people: [],
      groups: [],
      recursive: true
    }
  },
  methods: {
    onShow() {
      this.setGroups(this.userRead, this.groupRead, this.node.groupRead);
      this.setGroups(this.userWrite, this.groupWrite, this.node.groupWrite);
      client.getSharingInfo()
        .then(res => {
          setArray(this.people, res.people);
          setArray(this.groups, res.groups);
        });
    },
    setGroups(userArr, groupArr, nodeArr) {
      userArr.splice(0, userArr.length);
      groupArr.splice(0, groupArr.length);
      for (let group of nodeArr.split(' ')) {
        if (group.startsWith('people.')) {
          userArr.push(group.substring('people.'.length).replaceAll('\\', ''));
        } else if (group.trim() !== '') {
          groupArr.push(group.replaceAll('\\\\', '\\'));
        }
      }
    },
    share() {
      client.setNodeGroups({
        path: this.$store.state.nodeToShare.path,
        groupRead: this.groupRead,
        groupWrite: this.groupWrite,
        userRead: this.userRead,
        userWrite: this.userWrite,
        recursive: this.recursive
      }).then(() => {
        // Reload current path
        this.$bvModal.hide('share-modal');
        this.$store.dispatch('setPath', this.$store.state.path);
      });
    }
  }
}
</script>

<style>
#share-modal .badge {
  font-size: 100%;
}
</style>
