import { AfterViewInit, Component, Inject, OnDestroy, ViewChild } from '@angular/core';
import { Subscription } from 'rxjs';
import { Globals } from '../../../services/globals';
import { ENVIRONMENT_TOKEN, IENVIRONMENT } from '../../../injection-tokens';
import { AuthorizeService } from '../../../services/authorize.service';
import { HenselTranslateService } from '../../../services/localization/hensel-translate.service';
import { MAT_DIALOG_DATA, MatDialogRef } from '../../../components/angular-material-index';
import { HenselInputComponent } from '@app_core/components/hensel-input/hensel-input.component';


@Component({
  selector: 'app-login-popup',
  templateUrl: 'login-popup.component.html',
  styleUrls: ['login-popup.component.scss'],
})

export class LoginPopupComponent implements AfterViewInit, OnDestroy {
  public static LOGIN_IS_SHOWN: boolean = false;
  public overHeader: string;
  public header: string;
  public errorMsg: string;
  public hide: boolean = true;
  public authorizationService: AuthorizeService;
  private userSubscription: Subscription;
  public showSpinner: boolean = false;

  constructor(
    public dialogRef: MatDialogRef<LoginPopupComponent>,
    public globals: Globals,
    public translate: HenselTranslateService,
    @Inject(MAT_DIALOG_DATA) data: any,
    @Inject(ENVIRONMENT_TOKEN) public environment: IENVIRONMENT
  ) {
    this.overHeader = this.globals.appTitleWithVersion;
    this.header = translate.instant('core.caption.registration');
    this.errorMsg = data.errorMsg;
    this.authorizationService = data.authorizationService;
    this.userSubscription = this.authorizationService.loginAction$.subscribe((resultObject) => {
      this.showSpinner = false;
      if (resultObject.result) this.close();
      else {
        this.errorMsg = resultObject.errMsg;
      }
    });
  }


  ngAfterViewInit(): void {
    LoginPopupComponent.LOGIN_IS_SHOWN = true;
  }


  close() {
    this.dialogRef.close();
  }


  ngOnDestroy() {
    this.userSubscription.unsubscribe();
    LoginPopupComponent.LOGIN_IS_SHOWN = false;
    // if (!this.authorizationService.isLoggedIn()) this.authorizationService.loginPopup(); - is not realy needed
  }

  login(loginname: string, passw: string) {
    if (!loginname || !passw) return;
    this.showSpinner = true;
    this.authorizationService.login(loginname, passw);
  }

}
