import { Injectable } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { filter, map, mergeMap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class TitleService {

  constructor(private router:Router,
              private activatedRoute:ActivatedRoute,
              private titleService:Title) { 
      this.router.events.pipe(
        filter((event) => event instanceof NavigationEnd),
        map(() => this.activatedRoute),
        map((route) => {
          while (route.firstChild) route = route.firstChild;
          return route;
        }),
        mergeMap((route) => route.data)
      ).subscribe((event) => this.titleService.setTitle(event['title'] + " - Hit a Wod"));
  }

  setDynamicTitle(title:string) {
    this.titleService.setTitle(this.titleService.getTitle().replace("%s", title));
  }

}
