/*
 * Copyright (C) 2018 Robert Bosch GmbH Copyright (C) 2018 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { AfterContentInit, Component, ContentChildren, HostBinding, Input, OnDestroy, QueryList } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { BreadcrumbComponent } from './breadcrumb/breadcrumb.component';

@Component({
  selector: 'bci-breadcrumbs',
  templateUrl: './breadcrumbs.component.html',
  styleUrls: ['./breadcrumbs.component.scss'],
})

/**
 * Display breadcrumbs, or ellipsis for intermediate breadcrumbs if there are too many.
 */
export class BreadcrumbsComponent implements AfterContentInit, OnDestroy {
  @HostBinding('class') classes = 'breadcrumbs';
  /**
   * Maximum number of breadcrumbs shown starting from the root.
   */
  @Input() fixedLead = 1;
  /**
   * Maximum number of breadscrumbs shown starting from the current page.
   */
  @Input() fixedTail = 2;
  @ContentChildren(BreadcrumbComponent) private breadcrumbs: QueryList<BreadcrumbComponent>;
  private componentDestroyed$ = new Subject<void>();

  ngOnDestroy(): void {
    this.componentDestroyed$.next();
    this.componentDestroyed$.complete();
  }

  ngAfterContentInit(): void {
    this.breadcrumbs.changes.pipe(takeUntil(this.componentDestroyed$)).subscribe(() => {
      this.breadcrumbs.forEach((breadcrumb, index) => (breadcrumb.omitted = !this.isShown(index)));
    });
  }

  protected isShown(index: number) {
    return index < this.fixedLead || index >= this.breadcrumbs.length - this.fixedTail;
  }
}
