import {Injectable} from "@angular/core";
import {Employee} from "./model/employee";
import {Subject} from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class AppState {
  private readonly KEY_AUTHENTICATED = "authenticated"
  private readonly KEY_AUTHENTICATION_EXPIRATION = "authentication-expiration"
  private readonly KEY_LOGGED_IN_EMPLOYEE = "logged-in-employee"

  authenticatedUser$ = new Subject<{ authenticated: boolean, authenticatedUser: Employee }>()

  get isAuthenticated(): boolean {
    return sessionStorage.getItem(this.KEY_AUTHENTICATED) === "true"
  }

  set isAuthenticated(value: boolean) {
    sessionStorage.setItem(this.KEY_AUTHENTICATED, value.toString())
    this.authenticatedUser$.next({
      authenticated: value,
      authenticatedUser: this.authenticatedEmployee
    })
  }

  get authenticationExpiration(): number {
    return parseInt(sessionStorage.getItem(this.KEY_AUTHENTICATION_EXPIRATION))
  }

  set authenticationExpiration(value: number) {
    sessionStorage.setItem(this.KEY_AUTHENTICATION_EXPIRATION, value.toString())
  }

  get authenticatedEmployee(): Employee {
    const employeeString = sessionStorage.getItem(this.KEY_LOGGED_IN_EMPLOYEE)
    return employeeString ? JSON.parse(employeeString) : null
  }

  set authenticatedEmployee(value: Employee) {
    if (value === null) {
      sessionStorage.removeItem(this.KEY_LOGGED_IN_EMPLOYEE)
    } else {
      sessionStorage.setItem(this.KEY_LOGGED_IN_EMPLOYEE, JSON.stringify(value))
    }
    this.authenticatedUser$.next({
      authenticated: this.isAuthenticated,
      authenticatedUser: value
    })
  }
}
