import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {User} from '../models/user';
import {LoginService} from '../../shared/api/endpoints/services/login.service';
import {ToastService} from '../../shared/services/toast.service';

@Injectable({
  providedIn: 'root'
})
export class UserState {
  private userState$: BehaviorSubject<User> = new BehaviorSubject<User>(null);

  constructor(
    private loginService: LoginService,
    private toastService: ToastService
  ) {}

  setUser(user: User): void {
    this.userState$.next(user);
  }

  setLoggedIn(loggedIn: boolean) {
    this.userState$.next({...this.userState$.getValue(), isLoggedIn: loggedIn})
  }

  getUser(): User {
    return this.userState$.getValue();
  }

  /**
   * Get user, if not exists fetch from server
   * @param refresh force refresh user status from backend
   */
  getUser$(refresh: boolean = false): Observable<User> {
   if (this.userState$.getValue()){
      this.loginService.getUserInfo$Response().subscribe(res => {
        this.userState$.next({...this.userState$.getValue(), userInfo: res.body});
      }, err => this.toastService.showError(err.error.message));
   }
    return this.userState$.asObservable();
  }

  getLoggedIn(): boolean {
    return this.userState$.getValue().isLoggedIn;
  }
}
