import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { OAuthService } from 'angular-oauth2-oidc';
import { Subject, takeUntil } from 'rxjs';

@Component({
  selector: 'app-login',
  templateUrl: './login.html',
  styleUrl: './login.scss'
})
export class Login implements OnInit, OnDestroy {

  private readonly _destroy: Subject<void> = new Subject<void>();

  constructor(readonly as: OAuthService, readonly router: Router) { }

  ngOnInit(): void {
    if (this.as.hasValidAccessToken() && this.as.hasValidIdToken()) {
      this.getUserInfo();
    } else {
      this.as.events
        .pipe(
          takeUntil(this._destroy))
        .subscribe(event => {
          if (event.type === 'token_received')
            if (this.as.hasValidIdToken()) {
              this.getUserInfo();
            }
        });
    }
  }

  ngOnDestroy(): void {
    this._destroy.next();
    this._destroy.complete();
  }
  getUserInfo(): void {
    this.as.loadUserProfile()
      .then(_ => {
        this.router.navigate(['content', 'items']);
      })
      .catch(_ => this.router.navigate(['content', 'items']));
  }
}
