
import {of as observableOf,  Observable } from 'rxjs';

import {filter, mergeMap, distinctUntilChanged, map} from 'rxjs/operators';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { BreadcrumbItem } from './definition/breadcrumb-item';
import { BreadCrumbResolverService } from './service/breadcrumb.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
	selector: 'app-breadcrumb',
	templateUrl: './breadcrumb.component.html',
	styleUrls: ['./breadcrumb.component.scss']
})
export class BreadcrumbComponent implements OnInit {
	breadcrumbs$ = this.router.events.pipe(
		filter(event => event instanceof NavigationEnd),
		distinctUntilChanged(),
		mergeMap(event => this.buildBreadCrumb(this.activatedRoute.root)),);


	constructor(
		public activatedRoute: ActivatedRoute,
		private router: Router,
		private breadCrumbService: BreadCrumbResolverService,
		private language: TranslateService,
	) {
	}

	ngOnInit() {
	}

	buildBreadCrumb(route: ActivatedRoute): Observable<BreadcrumbItem[]> {
		if (this.breadCrumbService.resolve(route)) {
			return this.breadCrumbService.resolve(route).pipe(map(x => {
				x.unshift({
					label: this.language.instant('NAV-BAR.HOME'),
					url: '/home',
					icon: 'dashboard'
				}); return x;
			}));
		}
		return observableOf([]);
	}

	navigate(url, params) {
		this.router.navigate([url, params]);
	}
}
