import {ChangeDetectorRef, Component, DoCheck, OnInit} from "@angular/core";
import {HttpClient, HttpXsrfTokenExtractor} from "@angular/common/http";
import {AuthenticationService} from "../../security/authentication.service";
import {AppConfigService} from "@webbpm/base-package";

@Component({
  moduleId: module.id,
  selector: "[log-out]",
  templateUrl: "../../../../../src/resources/template/app/component/log_out.html"
})
export class LogOutComponent implements OnInit, DoCheck{
  private static readonly BACKEND_URL: string = "backend.url";
  private static readonly BACKEND_CONTEXT: string = "backend.context";
  private static readonly LOGOUT_URL_POSTFIX: string = "/esia/logout";

  private userFullname: string;
  private orgUnitName: string;
  csrfValue: any;
  formAction: any;

  constructor(private httpClient: HttpClient,
              private authenticationService: AuthenticationService,
              private appConfigService: AppConfigService,
              private tokenExtractor: HttpXsrfTokenExtractor,
              private cd: ChangeDetectorRef) {
    let backendUrl = this.appConfigService.getParamValue(LogOutComponent.BACKEND_URL);
    let backendContext = this.appConfigService.getParamValue(
        LogOutComponent.BACKEND_CONTEXT);

    if (backendUrl) {
      this.formAction = `${backendUrl}${LogOutComponent.LOGOUT_URL_POSTFIX}`;
    }
    else if (backendContext) {
      this.formAction = `/${backendContext}${LogOutComponent.LOGOUT_URL_POSTFIX}`;
    }
  }

  ngDoCheck(): void {
    this.csrfValue = this.tokenExtractor.getToken();
  }

  ngOnInit(): void {
    this.csrfValue = this.tokenExtractor.getToken();
    let isAuth = this.authenticationService.isAuthenticated();
    if (isAuth) {
      Promise.all([
                    this.httpClient.get<string>("esia/userfullname").toPromise(),
                    this.httpClient.get<string>("esia/orgunitname").toPromise()
                  ]).then(([userFullname, orgUnitName]) => {
        this.userFullname = userFullname;
        this.orgUnitName = orgUnitName;
        this.cd.markForCheck();
      });
    }
  }

  public getUserFullname(): string {
    return this.userFullname;
  }

  public isAuthenticated(): boolean {
   return this.authenticationService.isAuthenticated();
  }

  public getOrgUnitName(): string {
    return this.orgUnitName;
  }
}
