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

import { HttpClient } from '@angular/common/http';
import { Component, Inject } from '@angular/core';
import {
  AccessControlAuthenticationService,
  AUTH_OPTIONS,
  AuthenticationService,
  AuthorizationService,
  IAuthModuleConfig,
  MacmaAuthenticationService,
} from '@bci-web-core/auth';
import { tap } from 'rxjs/operators';
import { DemoAuthService } from '../services/demo-auth.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'bci-app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent {
  offerWinLogin: boolean;
  canRead: Observable<boolean>;
  canExecute: Observable<boolean>;

  constructor(
    public demoAuthService: DemoAuthService,
    private _authorizationService: AuthorizationService,
    private _authenticationService: AuthenticationService,
    @Inject(AUTH_OPTIONS) private authConfig: IAuthModuleConfig,
    private _httpClient: HttpClient,
  ) {
    this.offerWinLogin = this._authenticationService instanceof AccessControlAuthenticationService;

    this.canRead = this._authorizationService.canReadObservable(
      '$all.users',
      '7311ea8c-5d48-43fe-acf9-980eedf24b6c',
      'macma',
      'urn:com:bosch:bci:macma:entity:users'
    );
    this.canExecute = this._authorizationService.canExecuteObservable(
      '$all.users',
      '7311ea8c-5d48-43fe-acf9-980eedf24b6c',
      'macma',
      'urn:com:bosch:bci:macma:entity:users'
    );

    this.canRead.subscribe((allowed) => console.log('Can read privilege:' + allowed));
    this.canExecute.subscribe((allowed) => console.log('Can execute privilege:' + allowed));
  }

  makeRequest() {
    const endpoint =
      this._authenticationService.getIdTokenPayload().iss +
      (this._authenticationService instanceof MacmaAuthenticationService
        ? '/protocol/openid-connect/userinfo'
        : '/api/v1/ResourceSets/ControlPanel');

    this._httpClient
      .get(endpoint)
      .pipe(tap((t) => console.log(t)))
      .subscribe();
  }

  checkAuthorization() {
    const canRead = this._authorizationService.canRead(
      '$all.users',
      '7311ea8c-5d48-43fe-acf9-980eedf24b6c',
      'macma',
      'urn:com:bosch:bci:macma:entity:users'
    );

    alert('Can read all users: ' + canRead);
  }

  public stringify(t: any) {
    return JSON.stringify(t, null, 3);
  }

  public switchToAccessControl3() {
    sessionStorage.clear();
    window.location.href = '?auth-provider=accessControl3';
  }

  loginMacma() {
    (this._authenticationService as MacmaAuthenticationService).login();
  }
}
