/*
 * Copyright (C) 2018 Robert Bosch GmbH Copyright (C) 2018 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Params, Route, Router, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AuthenticationService } from './services/authentication.service';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard {
  constructor(private _router: Router, private _authService: AuthenticationService) {}

  canLoad(route: Route): Observable<boolean> {
    // TODO: skipWhenExpired beachten
    const url = `/${route.path}`;
    return this.checkLogin(url, null);
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    const url: string = state.url;
    return this.checkLogin(url, route.queryParams);
  }

  checkLogin(url: string, params: Params): Observable<boolean> {
    return this._authService.isAuthenticated().pipe(
      map((authenticated) => {
        if (authenticated) {
          return true;
        }

        this._authService.redirectUrl = url;

        if (params != null) {
          this._router.navigate(['/login'], { queryParams: params });
        } else {
          this._router.navigate(['/login']);
        }
        return false;
      })
    );
  }
}
