import { Injectable } from "@angular/core";
import { Account } from "../models/Account";
import { BehaviorSubject, Observable } from "rxjs";
import { HttpClient, HttpHeaders, HttpParams } from "@angular/common/http";

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

    private _user = new BehaviorSubject<Account>( new Account );
    user$ = this._user.asObservable();

    constructor( private http: HttpClient){ }

    getLoginState(): Observable<Account> {
        let sub = this.http.post<Account>( "api/account/loginState", {}, {} );
        sub.subscribe({
            next: data => {
                data.passwordHash = "";
                this._user.next(data);
            },
            error: err => {
                console.log("No login state found: ", err.error);
            }
        });
        return sub;
    }

    Logout(){
        this._user.next( new Account );
        return this.http.post<Account>( "api/account/logout", {}, { responseType: 'json' } );
    }

    get isLoggedIn(): boolean {
        return this._user.value.id != -1 ? true : false;
    }

    get loggedInUser(): Account {
        return this._user.value;
    }
}