import { HttpClient } from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable, of} from 'rxjs';
import {UserAuthRequest} from '../models/user-auth-request';

@Injectable({
  providedIn: 'root'
})
export class AuthServiceService {

  readonly AUTH_URL: string = 'http://localhost:8080/pa165/auth/login';
  readonly JWT: string = "JWT";
  readonly ROLE: string = "ROLE";

  readonly TEAM_MANAGER = "TEAM_MANAGER";
  readonly LEAGUE_MANAGER = "LEAGUE_MANAGER";

  authenticated: boolean = false;
  leagueManager: boolean = false;
  teamManager: boolean = false;

  constructor(private http: HttpClient) {
  }

  authenticate(userAuthRequest: UserAuthRequest, callback : Function) {
    this.http.post(
      this.AUTH_URL, 
      userAuthRequest,
      {responseType : 'text'}
      )
      .subscribe((response: string) => {
          this.handleAuthResponse(response);
        callback()});
  }

  logOut(): Observable<boolean> {
    localStorage.removeItem(this.JWT)
    this.authenticated = false;
    this.teamManager = false;
    this.leagueManager = false;
    return of(true);
  }

  isAuthenticated(): Observable<boolean> {
    this.authenticated = localStorage.getItem(this.JWT) !== null;
    return of(this.authenticated);
  }

  isLeagueManager(): Observable<boolean> {
    return of(this.authenticated && localStorage.getItem(this.ROLE) == this.LEAGUE_MANAGER);
  }

  isTeamManager(): Observable<boolean> {
    return of(this.authenticated && localStorage.getItem(this.ROLE) == this.TEAM_MANAGER);
  }

  handleAuthResponse(response: string) : void {
    let parts = response.split(" ");
    let role = parts[1];
    console.log(parts[1]);
    let token = parts[2];
    localStorage.setItem(this.ROLE, role);
    localStorage.setItem(this.JWT, token);
  }

  getBearerHeader(): string {
    let token = localStorage.getItem(this.JWT);
    return token !== null ? `Bearer ${token}` : "";
  }
}