import { Component, OnInit } from '@angular/core';
import {
  ActivatedRoute, NavigationEnd,
  Router
} from '@angular/router';
import { BreadCrumbModel } from '@shared/ui/models/breadcrumb.model';
import { ConfigService } from '@shared/config/config.service';
import { OrderingService } from '@shared/ui-api/ordering.service';
import { RouteBreadCrumbsHelper } from '@shared/ui-api/helpers/route-breadcrumbs-helper';

@Component({
  selector: 'app-breadcrumbs',
  templateUrl: './breadcrumbs.component.html',
  styleUrls: ['./breadcrumbs.component.scss']
})
export class BreadcrumbsComponent implements OnInit {
  path: string;
  breadCrumbs: BreadCrumbModel[] = [];
  snapshotBreadCrumbDetail = null;

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private config: ConfigService,
    private ordering: OrderingService,
  ) {
  }

  getSnapshotBCDetail() {
    let snapshot = this.activatedRoute.snapshot;
    let detail = null;
    while (snapshot) {
      if (snapshot.firstChild?.data?.config?.getBreadCrumbDetail) {
        detail = snapshot.firstChild.data.config?.getBreadCrumbDetail(
          snapshot.firstChild?.data
        );
      }
      snapshot = snapshot.firstChild;
    }
    return detail;
  }

  changeBreads() {
    const breadCrumbsHelper = new RouteBreadCrumbsHelper(
      this.config,
      this.activatedRoute,
      this.ordering,
    );

    this.breadCrumbs = breadCrumbsHelper.getBreadcrumbs();
  }

  ngOnInit() {
    this.changeBreads();
    this.router.events.subscribe((event) => {
      // reload breadcrumbs when user navigates or when page breadcrumb detail changes (instance rename for example)
      if (event instanceof NavigationEnd)
        {if (this.config.hasPrevUrl()) {
          this.changeBreads();
        } else {
          const snapshotBCDetail = this.getSnapshotBCDetail();
          if (this.snapshotBreadCrumbDetail === null) {
            // initialize the value
            this.snapshotBreadCrumbDetail = snapshotBCDetail;
          }
          // if previous detail breadcrumbs are no longer valid, change them
          if (this.snapshotBreadCrumbDetail !== snapshotBCDetail) {
            this.changeBreads();
            this.snapshotBreadCrumbDetail = snapshotBCDetail;
          }
        }}
    });
  }

}
