import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { interval, Subscription } from 'rxjs';
import { Globals } from '../../services/globals';
import { ServerInfo } from '../../models/serverinfo';
import { AppLogsService } from '../../services/applogs.service';
import { AuthorizeService } from '../../services/authorize.service';
import { HenselTranslateService } from '../../services/localization/hensel-translate.service';
import { UINotifierService } from '../../services/notification/uinotifier.service';
import { PageLoadingService } from '../../services/pageloading.service';
import { ServerInfoService } from '../../services/serverinfo.service';
import { LoginPopupComponent } from './login-popup/login-popup.component';

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

export class LoginComponent implements OnInit, OnDestroy, AfterViewInit {

  public title: string;
  private userLoginSubscription: Subscription;
  public serverInfo: ServerInfo;
  private returnUrl: string;
  private connectionReadySubscription: Subscription;
  private checkLoginPopupSubscription: Subscription;
  constructor(
    public translate: HenselTranslateService,
    private globals: Globals,
    private serverInfoService: ServerInfoService,
    private routerService: Router,
    public authorizationService: AuthorizeService,
    private appLogsService: AppLogsService,
    private uiNotifier: UINotifierService,
    private route: ActivatedRoute,
    protected pageLoadingService: PageLoadingService,

  ) {
    this.title = this.globals.appTitle;
    this.userLoginSubscription = this.authorizationService.loginAction$.subscribe((resultObject) => {
      if (resultObject.result) {
        if (!this.globals.isTheMainPage(this.returnUrl) && this.authorizationService.isLoggedUserChanged()) this.returnUrl = '/' + globals.mainPage.path;
        const path = this.returnUrl; //'/' + globals.mainPage.path
        this.appLogsService.dlog('After login goto ' + path);
        this.routerService.navigate([path]);
      } else {
        if (this.authorizationService.loginStatus !== this.authorizationService.EN_LoginStatus_Password) {
          this.authorizationService.loginPopup(resultObject.errMsg); //show popup only if automatically authorization failed
        }
      }
    });
  }


  ngOnInit(): void {
    this.connectionReadySubscription = this.serverInfoService.connectionReady.subscribe((si: ServerInfo) => {
      if (si) {
        this.serverInfo = si;
        this.doLogin();
      }
    });

    this.checkLoginPopupSubscription = interval(500).subscribe(() => {
      if (this.serverInfo
        && !this.authorizationService.isLoggedIn()
        && this.authorizationService.loginStatus !== this.authorizationService.EN_LoginStatus_Unknown
        && !LoginPopupComponent.LOGIN_IS_SHOWN) {
        this.doLogin();
      }
    });
  }

  ngAfterViewInit() { }

  private doLogin() {
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'];
    this.appLogsService.dlog('show login', this.authorizationService.user);
    if (!this.returnUrl) this.returnUrl = '/' + this.globals.mainPage.path;

    if (this.authorizationService.loginStatus === this.authorizationService.EN_LoginStatus_Unknown) { //first time is called
      this.authorizationService.login();
    } else {
      this.serverInfoService.serverInfoVisible = this.serverInfoService.defaultServerInfoVisible || this.serverInfoService.serverInfoVisible;
      this.authorizationService.loginPopup(null, true /* clears last used login and calls logout$ event */);
    }
  }

  ngOnDestroy() {
    this.userLoginSubscription?.unsubscribe();
    this.connectionReadySubscription?.unsubscribe();
    this.checkLoginPopupSubscription?.unsubscribe();

  }
}
