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

@Injectable({
  providedIn: 'root'
})

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

  @Output() getLoggedInState: EventEmitter<any> = new EventEmitter();
  constructor(private httpClient: HttpClient) { }
  public userLogin(username: string, password: string) {
    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) {
    return this.httpClient.post<any>(this.baseUrl + '/register.php', { name, email, pwd, username })
      .pipe(map(user => {
        return user;
      }));
  }

  setToken(token: string) {
    localStorage.setItem('sfcode_user_token_2n1289bpxd', token);
  }
  getToken() {
    return localStorage.getItem('sfcode_user_token_2n1289bpxd');
  }
  deleteToken() {
    localStorage.removeItem('sfcode_user_token_2n1289bpxd');
  }
  isLoggedIn() {
    const userToken = this.getToken();
    if (userToken != null) {
      return true
    }
    return false;
  }
}