<template>
<nav aria-label="breadcrumb" id="groups-breadcrumbs">
  <ol class="breadcrumb">
    <li class="breadcrumb-item" v-for="group in groups" v-bind:class="{ active: group.active }" v-bind:key="group.groupId">
      <a href="#" v-on:click="changeBreadcrumb(group.groupId)" v-if="!group.active">{{group.groupName}}</a>
      <span v-if="group.active">{{group.groupName}}</span>
    </li>
  </ol>
  <span id="breadcrumb-buttons">
    <a href="#" v-on:click.stop.prevent="openEditGroupModal(currentGroup)" title="Edit" v-if="currentGroup && isAdmin && currentGroup.groupId !== 'ROOT'">
      <font-awesome-icon icon="edit"></font-awesome-icon>
    </a>
    &nbsp;
    <a v-if="currentGroup" :href="'group/status?groupId=' + currentGroup.groupId" :download="currentGroup.groupName + '.csv'" title="Download CSV">
      <font-awesome-icon icon="download"></font-awesome-icon>
    </a>
  </span>
</nav>
</template>

<script>
import { mapState } from 'vuex';

function buildItems(values) {
  let groups = [];

  for (let i = 0; i < values.length; i++) {
    let group = values[i];
    group.active = false;
    groups.push(group);
  }

  // Activate the last item
  if (groups.length > 0) {
    groups[groups.length - 1].active = true;
  }

  return groups;
}

export default {
  name: 'GroupsBreadcrumb',
  computed: mapState({
    model: state => state.model,
    input: state => state.input,
    groups: state => buildItems(state.model.breadcrumbs),
    isAdmin: state => state.model.permission === 'ADMIN',
    currentGroup: state => state.model.breadcrumbs[state.model.breadcrumbs.length - 1]
  }),
  methods: {
    changeBreadcrumb: function(groupId) {
      this.$store.dispatch('changeBreadcrumb', groupId);
    },
    openEditGroupModal: function(group) {
      group.leaf = this.model.leaf;
      this.$parent.$refs.editGroupModal.openEditGroupModal(group, false);
    }
  }
}
</script>

<style scoped>
#groups-breadcrumbs {
  margin-top: 10px;
  position: relative;
}

#breadcrumb-buttons {
  position: absolute;
  right: 18px;
  top: 12px;
}
</style>
