import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import {HttpClient} from "@angular/common/http";
import {UserInformation} from "../../models/user-information";
import {Observable} from "rxjs";
import {Router} from "@angular/router";
import {RoutePath} from "../../enum/route-path";

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

  url = environment.backendUrl;

  private _token: any = null;

  constructor(private http: HttpClient,
              private router: Router) { }

  //#region LOGIN
  login(username: string,  password: string): any {
    const dto = {
        username,
        password
    }
    return this.http.post(this.url + '/auth/login', dto);
  }

  logout(): any {
    return this.http.post(this.url + '/logout', null)
      .subscribe(() => {
        this.setAuthenticationToken(null);
        this.router.navigate([RoutePath.SLASH]);
      })

  }
  //#endregion


  //#region httpHeaderBuilder
  public setAuthenticationToken(data: string | null) {
    this._token = data;
    if (data === null){
      localStorage.removeItem('token');
    } else {
      localStorage.setItem('token', this._token);
    }
  }

  public getAuthToken(): any {
    return (this._token !== null && this._token !== undefined) ? this._token: localStorage.getItem('token');
  }
  //#endregion

  public getUserDetails(username: string): Observable<UserInformation> {
    return this.http.get<UserInformation>(`${this.url}/user/${username}`);
  }
}
