import { ConfigService } from '../../config/config.service';
import { RouteHelper } from '../route-helper';
import { ActivatedRoute } from '@angular/router';
import { BreadCrumbModel } from '../../ui/models/breadcrumb.model';
import { OrderingService } from '../ordering.service';

export class RouteBreadCrumbsHelper {
  routeHelper: RouteHelper;

  constructor(private config: ConfigService, private activatedRoute: ActivatedRoute,
              private ordering?: OrderingService) {
    this.routeHelper = new RouteHelper(this.activatedRoute);
  }

  public getBreadcrumbs(): BreadCrumbModel[] {
    const breadcrumbs = [];
    let snapshot = this.activatedRoute.snapshot;
    let firstSegmentSkipped = false;
    let url = this.config.getPanelHomeUrl();
    let display = $localize`Home`;

    if (url === '/') {
      display = $localize`Home`;
    } else {
      snapshot = snapshot.firstChild;
    }
    breadcrumbs.push({display, url});
    url = '';

    while (snapshot) {
      const hide = snapshot.url.length === 0 || !!snapshot.data.hideInBreadcrumbs;
      if (firstSegmentSkipped === false) {
        firstSegmentSkipped = !!snapshot.data.includeFirstSegment;
      }

      if (snapshot.url.length) {
        if (url.length > 0) {
          url += '/';
        }
        url += snapshot.url[0].path;
      }

      if (!hide) {
        if (firstSegmentSkipped) {
          display = snapshot.url[0].path;

          if (snapshot.data.config && snapshot.data.config.getBreadCrumbDetail) {
            try {
              display = snapshot.data.config.getBreadCrumbDetail(snapshot.data);
            } catch (e) {
              if (e instanceof TypeError) {
                // ignore TypeError (object missing most likely) so we can show breadcrumbs on 404
              } else {
                console.error('Exception when getting breadcrumb details: ' + e.message);
              }
            }
          } else {
            display = display.charAt(0).toUpperCase() + display.slice(1);
          }

          if (snapshot.firstChild) {
            display = display.replace('-', ' ');
          }

          const queryParams = this.ordering.getQueryParams(url) || {};
          if (snapshot.data.config && snapshot.data.config.getBreadCrumbQueryParams) {
            const routeQueryParams = snapshot.data.config.getBreadCrumbQueryParams(snapshot);
            Object.assign(queryParams, routeQueryParams);
          }

          const breadcrumb = {display, url: this.config.getPanelUrl(url), queryParams};
          breadcrumbs.push(breadcrumb);
        } else {
          firstSegmentSkipped = true;
        }
      }

      snapshot = snapshot.firstChild;
    }

    if (breadcrumbs.length > 0) {
      delete breadcrumbs[breadcrumbs.length - 1].url;
    }
    return breadcrumbs;
  }
}
