import {Injectable} from '@angular/core';
import {Authorization} from "../models/Authorization";
import {BehaviorSubject} from "rxjs";

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    private authorization?: Authorization;
    private authorizationSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);

    constructor() {
      this.initAuthorization();
    }

    initAuthorization() {
        const storage = sessionStorage.getItem("authorization");
        try {
            this.setAuthorization(JSON.parse(storage || "") as Authorization);
        }
        catch (ex) {
            console.info("No user in sessionStorage")
            this.removeAuthorization();
        }
    }

    setAuthorization(authorization: Authorization) {
        sessionStorage.setItem("authorization", JSON.stringify(authorization)) ;
        this.authorization = authorization;
        this.authorizationSubject.next(this.authorization);
    }

    removeAuthorization() {
        this.authorization = undefined;
        sessionStorage.removeItem("authorization");
        this.authorizationSubject.next(this.authorization);
    }

    onAuthChange() {
        return this.authorizationSubject;
    }

    isLoggedIn() {
        return this.authorization && this.authorization.authenticated;
    }
}
