<script>
  import { get } from 'lodash';

  const ITEMS_AFTER_TRUNCATION = 3; // items are partitioned in the format [0], [rest of the items - ITEMS_AFTER_TRUNCATION], [ITEMS_AFTER_TRUNCATION]

  const isBreadcrumbItem = node => get(node, 'componentOptions.tag') === 'el-breadcrumb-item';

  export default {
    name: 'ElBreadcrumb',

    provide() {
      return {
        elBreadcrumb: this
      };
    },

    mounted() {
      const items = this.$el.querySelectorAll('.el-breadcrumb__item');
      if (items.length) {
        items[items.length - 1].setAttribute('aria-current', 'page');
      }
    },

    render() {
      const breadcrumbItems = this.$slots.default && this.$slots.default.length
        ? this.$slots.default.filter(vnode => isBreadcrumbItem(vnode))
        : [];
      const [itemsBeforeTruncation, itemsBeingTruncated, itemsAfterTruncation] = [[], [], []];

      // partition the passed items into arrays of lengths
      // `1`, `length - 1 - ITEMS_AFTER_TRUNCATION`  and `ITEMS_AFTER_TRUNCATION` respectively
      for (let item of breadcrumbItems) {
        if (itemsBeforeTruncation.length < 1) itemsBeforeTruncation.push(item);
        else if (itemsAfterTruncation.length < ITEMS_AFTER_TRUNCATION) itemsAfterTruncation.push(item);
        else {
          itemsBeingTruncated.push(itemsAfterTruncation.shift());
          itemsAfterTruncation.push(item);
        }
      }

      // no need to add the dropdown if only a single item is being truncated
      const truncatedItemsComponent = itemsBeingTruncated.length > 1 ? (
        <el-breadcrumb-item>
          <el-dropdown placement="bottom">
            <a class="el-dropdown-link">
              &nbsp;<fa-icon icon={['far', 'ellipsis-h']}></fa-icon>&nbsp;
            </a>
            <el-dropdown-menu class="el-breadcrumb__truncation-dropdown" slot="dropdown">
              {itemsBeingTruncated.map(item => (
                <el-dropdown-item>{item}</el-dropdown-item>
              ))}
            </el-dropdown-menu>
          </el-dropdown>
        </el-breadcrumb-item>
      ) : itemsBeingTruncated;

      return (
        <div class="el-breadcrumb" aria-label="Breadcrumb" role="navigation">
          { itemsBeforeTruncation }
          { truncatedItemsComponent }
          { itemsAfterTruncation }
        </div>
      );
    }
  };
</script>
