import {Component, OnInit, OnDestroy} from '@angular/core';
import {NavController} from '@ionic/angular';
import {Router} from '@angular/router';
import {IAuthAction} from 'ionic-appauth';
import {Subscription} from 'rxjs';
import {PAIAAuthService} from '../../paia-auth.service';

@Component({
  selector: 'auth-callback',
  templateUrl: './auth-callback-page.component.html',
  styleUrls: ['./auth-callback-page.component.scss'],
})
export class PAIAAuthCallbackPageComponent implements OnInit, OnDestroy {
  sub: Subscription;

  constructor(
    private auth: PAIAAuthService,
    private navCtrl: NavController,
    private router: Router,
  ) {}

  ngOnInit() {
    this.sub = this.auth.events$.subscribe(action => this.postCallback(action));
    this.auth.authorizationCallback(window.location.origin + this.router.url);
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

  async postCallback(_action: IAuthAction) {
    this.navCtrl.navigateRoot('profile');
  }
}
