<template>

  <div class="itf-tree-view d-grid">
    <itf-button
      @click="onSelect(node)"
      v-for="({ node, depth }, n) of list"
      :key="n"
      :class="{ [`depth-${depth}`]: true, 'active': value === node[itemKey] }"
      class="align-items-center d-flex gap-2 py-2" aria-current="true">
      <slot name="prepend" :item="node"></slot>
      <div class="d-flex align-items-start gap-2 w-100 justify-content-between">
        <div>
          <slot name="item" :item="node"></slot>
        </div>
        <slot name="append" :item="node"></slot>
      </div>
    </itf-button>
  </div>

</template>
<script>
import { Vue, Component, Model, Inject, Prop } from 'vue-property-decorator';
import itfIcon from '../icon/Icon';
import itfButton from '../button/Button';

export default @Component({
  name: 'itfTreeView',
  components: {
    itfIcon,
    itfButton
  }
})
class itfTreeView extends Vue {
  @Inject({ default: null }) itemLabel;
  @Model('input') value;
  @Prop(Array) items;
  @Prop({ type: String, default: 'Id' }) itemKey;
  @Prop({ type: String, default: 'ParentId' }) itemParentKey;

  onSelect(item) {
    this.$emit('input', item[this.itemKey]);
  }

  get list() {
    if (!this.items || !this.items.length) {
      return [];
    }
    const root = this.items.find((item) => item[this.itemKey] === null);
    if (!root) {
      throw new Error('Root not found');
    }
    function fillListWithNodes(items, node, itemKey, parentKey, depth = 0) {
      const list = items
        .filter((item) => item[parentKey] === node[itemKey])
        // eslint-disable-next-line max-len
        .reduce((acc, childNode) => acc.concat(fillListWithNodes(items, childNode, itemKey, parentKey, depth + 1)), []);
      return [{ node, depth }, ...list];
    }
    return fillListWithNodes(this.items, root, this.itemKey, this.itemParentKey);
  }
}
</script>
