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

import { Injectable } from '@angular/core';
import {
  AccessControlAuthenticationService,
  AccessControlAuthResponse,
  AuthenticationService,
  AuthorizationService,
  ResourceSet,
  User,
} from '@bci-web-core/auth';
import { Observable, of } from 'rxjs';
import { map, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class DemoAuthService {
  constructor(
    private _authenticationService: AuthenticationService,
    private _authorizationService: AuthorizationService
  ) {}

  public get username$(): Observable<string> {
    return of(this._authenticationService.getUsername());
  }

  public get user$(): Observable<User> {
    return this._authenticationService instanceof AccessControlAuthenticationService
      ? this._authenticationService.getUser()
      : of(undefined);
  }

  public get idToken$(): Observable<any> {
    return this._authenticationService
      .isAuthenticated()
      .pipe(map(() => this._authenticationService.getIdTokenPayload()));
  }

  public get accessToken$(): Observable<any> {
    return this._authenticationService.getAccessToken();
  }

  public get accessControlAuthResponse$(): Observable<AccessControlAuthResponse> {
    return this._authenticationService instanceof AccessControlAuthenticationService
      ? this._authenticationService.getAccessControlAuthResponse()
      : of(undefined);
  }

  public get isExpired$(): Observable<boolean> {
    return this.expiration$.pipe(map((expiration) => expiration.getTime() < new Date().getTime()));
  }

  public get isAuthenticated$(): Observable<boolean> {
    return this._authenticationService.isAuthenticated();
  }

  public get expiration$(): Observable<Date> {
    return this._authenticationService.getExpiration().pipe(map((expiresAt) => new Date(expiresAt)));
  }

  public get ressourceSets(): Observable<ResourceSet[]> {
    return this._authorizationService.getResourceSets();
  }

  public get roles$(): Observable<string[]> {
    return this._authenticationService.getRoles();
  }

  public logout(): void {
    this._authenticationService
      .logout()
      .pipe(
        tap(() => {
          console.log('logged out');
        })
      )
      .subscribe();
  }
}
