import { Component } from '@angular/core';
import { TokenStorageService } from "./auth/token-storage.service";
import { NavigationEnd, Router } from "@angular/router";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Grade-book';
  private roles?: string[];
  authority?: string;

  constructor(private tokenStorage: TokenStorageService, private token: TokenStorageService, private router: Router) {
    this.setAuthorities();
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.setAuthorities();
      }
    })
  }

  setAuthorities(): void {
    if (this.tokenStorage.getToken()) {
      this.roles = this.tokenStorage.getAuthorities();
      this.roles.every(role => {
        if (role === 'ROLE_ADMIN') {
          this.authority = 'admin';
          return false;
        }
        this.authority = 'user';
        return true;
      });
    }
  }

  logout() {
    this.token.signOut();
    window.location.reload();
  }

  public getAuthority() {
    return this.authority;
  }

}
