import { BehaviorSubject, Observable } from 'rxjs';
import { User } from '../models/user.model';
import { Injectable } from '@angular/core';
import { HitAWodService } from './hit-a-wod.service';
import { TokenService } from './token.service';

@Injectable({ providedIn: 'root' })
export class UserService {
    private currentUserSubject: BehaviorSubject<User>;
    public currentUser: Observable<User>;

    constructor(private api:HitAWodService,
                private tokenService:TokenService) {
        const data = localStorage.getItem('haw-user');
        let user = (data!=null && data!=undefined) ? JSON.parse(data) : null;
        this.currentUserSubject = new BehaviorSubject<User>(user);
        this.currentUser = this.currentUserSubject.asObservable();
        const token = this.tokenService.get();
        
        if(!user && token) {
            this.api.me().toPromise().then(
                data => {
                    this.setUser(data);
                },
                error => {

                }
            );
        }

    }

    public get currentUserValue(): User {
        return this.currentUserSubject.value;
    }

    public setUser(user:User) {
        if(user!=null && user!=undefined) {
            localStorage.setItem('haw-user', JSON.stringify(user));
            this.currentUserSubject.next(user);
        }
    }

    public deleteUser() {
        localStorage.removeItem('haw-user');
        this.currentUserSubject.next(null);
    }
}