import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {CookieService} from "ngx-cookie";
import {AppConfigService} from "@webbpm/base-package";
import {map, tap} from "rxjs/operators";

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

  constructor(private http: HttpClient,
              private cookieService: CookieService,
              private appConfigService: AppConfigService) {
  }

  checkAuthentication(): Promise<any>{
    return this.appConfigService.load().then(() => this.http.get<any>("health").toPromise());
  }

  logout(): Promise<string> {
    return this.http.post<string>('esia/logout', {}).toPromise();
  }

  public isAuthenticated(): boolean {
    return this.cookieService.get('webbpm.ervu-lkrp-fl') != null;
  }

  public redirectToEsia() {
    return this.http.get<string>("esia/url").pipe(
        tap(url => {
          window.open(url, "_self");
        }),
        map(() => true)
    );
  }
}
