<!-- components/groups.vue -->
<template>
  <div>
    <section class="hero is-primary">
      <div class="hero-body">
        <div class="container has-text-centered">
          <h3>
            <div class="text-center">
              <font-awesome-icon class="float-left" icon="arrow-circle-left" @click="previousgroup()"/>
              <input type="number" style="font-size: small; max-width: 48px; text-align: center;"
                     v-model="new_group_id" @blur="manually_set_group_id()"
                     @input="manually_set_group_id()">
              <font-awesome-icon class="float-right" icon="arrow-circle-right" @click="nextgroup()"/>
            </div>
          </h3>

          <h3 class="title">{{ group.id }} – {{ group.name }}</h3>

          <p><strong>{{ $t('nickname') }}:&nbsp</strong>{{ group.nickname }}</p>
          <p><strong>{{ $t('first_name') }}:&nbsp</strong>{{ group.first_name }}</p>
          <p><strong>{{ $t('last_name') }}:&nbsp</strong>{{ group.last_name }}</p>

          <hr/>
          <!--<p v-if="profile.role"><strong>{{$t('role')}}:&nbsp</strong>{{profile.role}}</p>-->
          <p><strong>{{ $t('role') }}:&nbsp</strong><span v-if="group.role">{{ group.role }}</span><span
              v-else>{{ $t('no specific role') }}</span></p>
          <p><strong>{{ $t('groups') }}:&nbsp</strong><span v-for="g in group.groups">{{ g.name }}, </span></p>
          <p><strong>{{ $t('permissions') }}:&nbsp</strong></p>
          <ul>
            <li v-for="p in group.effective_permissions">{{ p.name }}</li>
          </ul>

          <hr/>

          <p class="subtitle error-msg">{{ errorMsg }}</p>
          <b-form inline @submit="delete_group">
            <b-button style="margin-right: 5px;" type="submit" :disabled="!delete_checked" variant="danger">{{ $t('delete.group') }}</b-button>
            <b-form-checkbox v-model="delete_checked">{{ $t('check.to.allow.deletion') }}</b-form-checkbox>
          </b-form>

        </div>
      </div>
    </section>

  </div>
</template>

<script>
import {EventBus} from '@/utils';
import {getRemainingJwtValiditySeconds} from '@/utils';
import getRepository from '@/api/RepositoryFactory';

const groupRepository = getRepository('group');

export default {
  props: ['group_id'],
  data() {
    return {
      current_group_id: this.group_id == null ? 1 : parseInt(this.group_id),
      current_group_index: null,
      new_group_id: this.current_group_id,
      isLoading: false,
      groups: [],
      delete_checked: false,
      errorMsg: '',
    };
  },
  methods: {
    fetch() {
      this.isLoading = true;
      // const { data } = await GroupRepository.get();
      groupRepository.getgroups()
          .then((response) => {
            this.groups = response.data;
            this.isLoading = false;
          });

    },
    calculate_current_group_index() {
      this.current_group_index = this.groupIds.findIndex((id) => {
        return id === this.current_group_id;
      });
    },
    previousgroup() {
      if (null == this.current_group_index) {
        this.calculate_current_group_index();
      }
      if (this.current_group_index === 0) this.current_group_index = this.groupIds.length - 1;
      else this.current_group_index = this.current_group_index - 1;
      this.current_group_id = this.groupIds[this.current_group_index];
      this.new_group_id = this.current_group_id;
    },
    nextgroup() {
      if (null == this.current_group_index) {
        this.calculate_current_group_index();
      }
      if (this.current_group_index === this.groupIds.length - 1) this.current_group_index = 0;
      else this.current_group_index = this.current_group_index + 1;
      this.current_group_id = this.groupIds[this.current_group_index];
      this.new_group_id = this.current_group_id;
    },
    manually_set_group_id() {
      if (this.new_group_id == null || this.new_group_id === '') {
        this.new_group_id = this.current_group_id;
        return;
      }
      if (this.groupIds.includes(parseInt(this.new_group_id))) {
        this.current_group_id = parseInt(this.new_group_id);
      }
      this.new_group_id = this.current_group_id;
    },
    delete_group(e){
      e.preventDefault();
      this.delete_checked = false;
      groupRepository.deletegroup(this.current_group_id)
          .then(()=>{
            this.fetch();
            this.nextgroup();
            EventBus.$emit('normalMessage', this.$t('group.deleted'));
          })
          .catch((error)=>{
            EventBus.$emit('errorMessage', this.$t('unable.to.delete.group') + ": "+ error.data.message);
          })
    },
    test(e){
      e.preventDefault();
      this.delete_checked = false;
      this.fetch();
      this.nextGroup();
      EventBus.$emit('normalMessage', 'test.msg');
    }
  },
  mounted() {
    this.fetch();
  },
  beforeDestroy() {
    // todo
  },
  computed: {
    columns() {
      if (this.groups.length === 0) {
        return [];
      }
      let columns = Object.keys(this.groups[0]);
      columns = columns.filter((value) => {  // filter to only show some fields
        return ["id", "first_name", "last_name", "email", "nickname", "role"].includes(value);
      });
      return columns;
    },
    group() {
      if (this.groups.length === 0) {
        return [];
      }
      return this.groups.filter((value) => value.id.toString() === this.current_group_id.toString()).pop();
    },
    groupIds() {
      let ids = [];
      this.groups.forEach((elem) => {
        ids.push(parseInt(elem.id));
      });
      return ids;
    },
  },
};
</script>

<style lang="scss">
.error-msg {
  color: red;
  font-weight: bold;
}
</style>
