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

export interface UserSession {
  userId: string,
  name: string,
  realm: string,
  domainId: string,
  permissions: 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;
  }

  hasAnyPermission(permissions: string[]): boolean {
    return this.isAuthorized() && permissions.some(role => this.getPermissions().includes(role));
  }

  hasPermission(permission: string): boolean {
    return this.isAuthorized() && this.getPermissions().includes(permission);
  }

  getUserId(): string{
    return this.isAuthorized() ? this.session.userId: null;
  }

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

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

  getDomainId(): string {
    return this.isAuthorized() ? this.session.domainId : null;
  }

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