import {Component, OnInit} from '@angular/core';
import {UserService} from "../../services/user.service";
import {OAuthEvent, OAuthService} from "angular-oauth2-oidc";
import {environment} from "../../../environments/environment";
import {AuthService} from "../../services/auth.service";

@Component({
    selector: 'app-login-oid',
    templateUrl: './login-oid.component.html',
    styleUrls: ['./login-oid.component.css']
})
export class LoginOidComponent implements OnInit {
    provider: string = environment.oidProvider;

    constructor(private userService: UserService, private authService: OAuthService, private appAuth: AuthService) {}

    ngOnInit(): void {
        // IMPORTANT: Entry point from OID provider. Token will not be present immediately. Must start the open id flow
        this.authService.events
            .subscribe((e: OAuthEvent) => {
                // TODO: Manage here other events if needed. Refer to angular-oauth2-oidc library
                if (e.type === 'token_received') {
                    this.userService.login();
                }

                if (e.type === 'logout') {
                    this.appAuth.removeAuthorization();
                }
            });

        // IMPORTANT: this reloads the open id flow and tries login, which fires the token_received handled in constructor
        this.userService.initOpenId();
    }
}
