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>(this.getUserFromStorage());
    user$ = this._user.asObservable();

    constructor( private http: HttpClient){ }

    Login(UserName: string, Password: string, StayLoggedIn: boolean): Observable<Account> {

        const body = new HttpParams()
            .set("UserName", UserName)
            .set("PasswordHash", Password)
            .set("StayLoggedIn", StayLoggedIn );
        const headers = new HttpHeaders({
            'Content-Type': 'application/x-www-form-urlencoded'
        });

        let sub = this.http.post<Account>( "api/account/login", body, { headers } );
        sub.subscribe({
            next: data => {
                data.passwordHash = "";
                this._user.next(data);
                this.setUserToStorage(data, StayLoggedIn == true ? SessionType.Forever : SessionType.Session);
            },
            error: err => {
                console.log("HTTP Error Signing In: ", err.error);
            }
        });
        return sub;
    }

    Logout(){
        this._user.next( new Account );
        this.delUserFromStorage();
        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;
    }

    private getUserFromStorage(): Account {
        const foreverUser = localStorage.getItem('user');
        const sessionUser = sessionStorage.getItem('user');
        let user = null;
        if (foreverUser != null){
            user = JSON.parse(foreverUser)
        } else if (sessionUser != null){
            user = JSON.parse(sessionUser)
        } else {
            user = new Account();
            user.id = -1;
        }
        return user;
    }
    private setUserToStorage(user: Account, session: SessionType): void {
        if (session == SessionType.Forever){
            localStorage.setItem('user', JSON.stringify(user));
        }else if(session == SessionType.Session){
            sessionStorage.setItem('user', JSON.stringify(user));
        }
    }
    private delUserFromStorage(): void {
        localStorage.removeItem('user');
        sessionStorage.removeItem('user');
    }

}

export enum SessionType {
    Forever,
    Session
}