/*
 * Copyright (C) 2021-2022 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, OnDestroy, OnInit} from '@angular/core';
import {IonicUserInfoHandler} from 'ionic-appauth';
import {DefaultAuthService} from '../../auth/default-auth.service';
import {Requestor, TokenResponse} from '@openid/appauth';
import {PAIAAuthService} from '../../auth/paia/paia-auth.service';
import {SCAuthorizationProviderType, SCUserConfiguration} from '../user';
import {Subscription} from 'rxjs';
import {AuthHelperService} from '../../auth/auth-helper.service';

@Component({
  selector: 'app-home',
  templateUrl: './profile-page.component.html',
  styleUrls: ['./profile-page.component.scss'],
})
export class ProfilePageComponent implements OnInit, OnDestroy {
  data: {[key in SCAuthorizationProviderType]: {loggedIn: boolean}} = {
    default: {loggedIn: false},
    paia: {loggedIn: false},
  };

  userInfo?: SCUserConfiguration;

  subscriptions: Subscription[] = [];

  constructor(
    private defaultAuth: DefaultAuthService,
    private paiaAuth: PAIAAuthService,
    private requestor: Requestor,
    private authHelperService: AuthHelperService,
  ) {}

  ngOnInit() {
    this.subscriptions.push(
      this.defaultAuth.token$.subscribe(_token => {
        this.defaultAuth
          .getValidToken()
          .then(token => {
            this.data.default.loggedIn = true;
            this.getUserInfo(token);
          })
          .catch(_error => {
            this.data.default.loggedIn = false;
          });
      }),
      this.paiaAuth.token$.subscribe(_token => {
        this.paiaAuth
          .getValidToken()
          .then(_token => {
            this.data.paia.loggedIn = true;
          })
          .catch(_error => {
            this.data.paia.loggedIn = false;
          });
      }),
    );
  }

  getUserInfo(token: TokenResponse) {
    const userInfoHandler = new IonicUserInfoHandler(this.requestor);

    userInfoHandler
      .performUserInfoRequest(this.defaultAuth.localConfiguration, token)
      .then(userInfo => {
        this.userInfo = this.authHelperService.getUserFromUserInfo(userInfo);
      });
  }

  public signIn() {
    this.defaultAuth.signIn();
  }

  signInPAIA() {
    this.paiaAuth.signIn();
  }

  async signOut() {
    await this.defaultAuth.signOut();
    this.userInfo = undefined;
  }

  async signOutPAIA() {
    await this.paiaAuth.signOut();
  }

  ngOnDestroy(): void {
    for (const subscription of this.subscriptions) {
      subscription.unsubscribe();
    }
  }
}
