/*
 * Copyright (C) 2023 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {Component} from '@angular/core';
import {NavController} from '@ionic/angular/standalone';
import {Router} from '@angular/router';
import {AuthActions, IAuthAction} from 'ionic-appauth';
import {AuthHelperService} from '../../auth-helper.service';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {Observable} from 'rxjs';
import {IPAIAAuthAction} from '../../paia/paia-auth-action';
import {DefaultAuthService} from '../../default-auth.service';

@Component({
  templateUrl: 'auth-callback-page.component.html',
  styleUrls: ['auth-callback-page.component.scss'],
})
export class AuthCallbackPageComponent {
  constructor(
    private navCtrl: NavController,
    private router: Router,
    private authHelper: AuthHelperService,
    private auth: DefaultAuthService,
  ) {
    const events: Observable<IPAIAAuthAction | IAuthAction> = this.auth.events$;

    events.pipe(takeUntilDestroyed()).subscribe((action: IAuthAction) => this.postCallback(action));
    this.auth.authorizationCallback(window.location.origin + this.router.url);
  }

  async postCallback(action: IAuthAction) {
    if (action.action === AuthActions.SignInSuccess) {
      const originPath = await this.authHelper.getOriginPath();
      this.navCtrl.navigateRoot(originPath ?? 'profile');
      this.authHelper.deleteOriginPath();
    }
    if (action.action === AuthActions.SignInFailed) {
      this.navCtrl.navigateRoot('profile');
    }
  }
}
