import {EventEmitter, Injectable, Output} from '@angular/core';
import {map} from 'rxjs/operators';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class ApiService {
  redirectUrl: string;
  baseUrl = 'http://localhost/sfcode/backend/';

  @Output() getLoggedInState: EventEmitter<any> = new EventEmitter();

  constructor(private httpClient: HttpClient) {
  }

  public userLogin(username: string, password: string): Observable<any> {
    return this.httpClient.post<any>(this.baseUrl + '/login.php', {username, password})
      .pipe(map(user => {
        if (user.length === 0) {
          throw new Error();
        }
        this.setToken(JSON.stringify(user));
        this.getLoggedInState.emit(true);
        return user;
      }));
  }

  public userReg(name, email, pwd, username): Observable<any> {
    return this.httpClient.post<any>(this.baseUrl + '/register.php', {name, email, pwd, username})
      .pipe(map(user => {
        return user;
      }));
  }

  setToken(token: string): void {
    localStorage.setItem('sfcode_user_token_2n1289bpxd', token);
  }

  getToken(): string {
    return localStorage.getItem('sfcode_user_token_2n1289bpxd');
  }

  deleteToken(): void {
    localStorage.removeItem('sfcode_user_token_2n1289bpxd');
  }

  isLoggedIn(): boolean {
    const userToken = this.getToken();
    return userToken != null;
  }
}
