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> {
        const headers = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });
        let sub = this.http.post<Account>( "api/loginState", {}, { headers } );
        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/logout", {}, { responseType: 'json' } );
    }

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

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

export enum SessionType {
    Forever,
    Session
}