import { DOCUMENT } from '@angular/common';
import { ChangeDetectionStrategy, Component, Inject } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { environment } from '@msfa-environment';
import { AuthenticationService } from '@msfa-services/api/authentication.service';
import { IdleService } from '@msfa-services/api/idle.service';
import { Observable } from 'rxjs';
import { filter, map, switchMap } from 'rxjs/operators';

@Component({
  selector: 'msfa-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
  userIsIdle$: Observable<boolean> = this.idleService.isIdle$;
  timeLeftBeforeLogout$: Observable<string> = this.idleService.timeLeftBeforeLogout$;

  constructor(
    @Inject(DOCUMENT) private document: Document,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private titleService: Title,
    private idleService: IdleService,
    private authenticationService: AuthenticationService
  ) {
    this.document.body.dataset.version = environment.version;

    this.router.events
      .pipe(
        filter(event => event instanceof NavigationEnd),
        map(() => traverseUntilNoChildRoute(this.activatedRoute)),
        switchMap((route: ActivatedRoute) => route.data)
      )
      .subscribe((routeData: { [title: string]: string }) => {
        const pageTitle = routeData.title;
        this.titleService.setTitle(`${pageTitle ? `${pageTitle} - ` : ''}Mina sidor för fristående aktörer`);
      });
  }

  logout(): void {
    this.authenticationService.logout();
  }

  setUserAsActive(): void {
    this.idleService.setActive();
  }
}

function traverseUntilNoChildRoute(route: ActivatedRoute): ActivatedRoute {
  while (route.firstChild) {
    route = route.firstChild;
  }
  return route;
}
