import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";
import {Subject} from "rxjs";

export interface UserSession {
  name: string,
  realm: string,
  recruitmentId: string,
  roles: string[]
}

@Injectable({providedIn: 'root'})
export class AuthorizationService {

  private session: UserSession;

  public onSessionUpdate: Subject<UserSession> = new Subject<UserSession>();

  constructor(protected httpClient: HttpClient) {}

  public getCurrentSession(): Promise<any> {
    if (this.session) return new Promise(resolve => resolve(this.session))
    return this.httpClient.get('session')
        .toPromise()
        .then((session: UserSession) => {
          this.session = session;
          this.onSessionUpdate.next(session);
          return session;
        })
  }

  isAuthorized(): boolean {
    return !!this.session;
  }

  hasAnyRole(roles: string[]): boolean {
    return this.isAuthorized() && roles.some(role => this.getRoles().includes(role));
  }

  getName(): string {
    return this.isAuthorized() ? this.session.name : null;
  }

  getRealm(): string {
    return this.isAuthorized() ? this.session.realm : null;
  }

  getRecruitmentId(): string {
    return this.isAuthorized() ? this.session.recruitmentId : null;
  }

  getRoles(): string[] {
    return this.isAuthorized() ? this.session.roles : null;
  }
}