import { filter, map } from 'rxjs/operators';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { ConfigService } from '../../config/config.service';
import { RouteHelper } from '@shared/ui-api/route-helper';
import { environment } from '@environments/environment';

export class TitleBuilder {
  routeHelper: RouteHelper;

  constructor(
    private titleService: Title,
    private router: Router,
    private config: ConfigService,
    private activatedRoute: ActivatedRoute
  ) {
    this.routeHelper = new RouteHelper(this.activatedRoute);
  }

  private getRouteTitle() {
    let title;
    const finalRoute = this.routeHelper.getFinalRoute();
    if (finalRoute.snapshot.data?.config?.getTitleDisplay) {
      // first, try to display title using related method
      try {
        title = finalRoute.snapshot.data.config.getTitleDisplay(finalRoute.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 title display: ' + e.message);
        }
      }
    } else if (finalRoute.snapshot.data?.config?.getBreadCrumbDetail) {
      // if title related method was not used, fallback to getBreadCrumbDetail to show a user-friendly text
      try {
        title = finalRoute.snapshot.data.config.getBreadCrumbDetail(finalRoute.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 if (finalRoute.snapshot.url.length !== 0) {
      if (environment.enableErrorLogging) {
        console.error('Route config getBreadCrumbDetail or getTitleDisplay (if no breadcrumbs) must be defined in route data');
      }
      title = finalRoute.snapshot.url[0]?.path || null;
      if (title) {
        title = title.charAt(0).toUpperCase() + title.slice(1);
      }
    }
    if (!title) {
      // title still not found, try to determine title from URL
      const urlSplit = this.routeHelper.getRoutePath().split('/');
      const lastUrlEntry = urlSplit[urlSplit.length - 1];
      if (lastUrlEntry) {
        if (this.config.getPanelHomeUrl().endsWith(lastUrlEntry)) {
          title = $localize`Home`;
        } else {
          title = lastUrlEntry.charAt(0).toUpperCase() + lastUrlEntry.slice(1);
        }
      } else {
        title = $localize`Home`;
      }
    }
    return title;
  }

  build() {
    this.router.events.pipe(
      filter((event) => event instanceof NavigationEnd),
      map(() => this.router)
    ).subscribe(() => {
        const title = `${this.config.current.settings.baseTitle}: ${this.getRouteTitle()}`;
        this.titleService.setTitle(title);
      }
    );
  }
}
