import { Component, OnDestroy, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { Idle } from '@ng-idle/core';
import { Keepalive } from '@ng-idle/keepalive';
import { Subscription } from 'rxjs';
import { environment } from 'src/environments/environment';
import { AppConfig } from './_providers/_domain/appconfig';
import { AppConfigService } from './_providers/_services/appconfigservice';
import { AuthService } from './_providers/_services/auth.service';
import { TimeOutDialogComponent } from './_window/time-out-dialog/time-out-dialog.component';
import { TranslateService } from "@ngx-translate/core";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {

  title = 'Tender';
  message: any = null;
  public subscription: Subscription;
  config: AppConfig;

  idleState = 'Not started.';
  timedOut = false;
  lastPing?: Date = null;
  displaySessionTimeOut: boolean = false;

  constructor(
    private idle: Idle,
    public router: Router,
    private keepalive: Keepalive,
    private configService: AppConfigService,
    private authenticationService: AuthService,
    public dialog: MatDialog,
    public translate: TranslateService,
  ) {
    translate.setDefaultLang('en-sales');
    translate.use('en-sales');

    // sets an idle timeout of 5 seconds, for testing purposes.
    idle.setIdle(environment.timeOutLimit);
    // sets a timeout period of 5 seconds. after 10 seconds of inactivity, the user will be considered timed out.
    idle.setTimeout(environment.timeOutCountLimit);
    // sets the default interrupts, in this case, things like clicks, scrolls, touches to the document
    // idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);

    idle.onIdleEnd.subscribe(() => {
      this.idleState = 'No longer idle.'
      console.log(this.idleState);
      this.reset();
    });

    idle.onTimeout.subscribe(() => {
      // this.childModal.hide();
      this.displaySessionTimeOut = false;
      this.idleState = 'Timed out!';
      this.timedOut = true;
      console.log(this.idleState);
      this.logout();
      // this.router.navigate(['/']);
    });

    idle.onIdleStart.subscribe(() => {
      this.idleState = 'You\'ve gone idle!'
      console.log(this.idleState);
      // this.childModal.show();
      this.displaySessionTimeOut = true;
      this.logout();
      this.openDialog();
    });

    idle.onTimeoutWarning.subscribe((countdown) => {
      this.idleState = 'You will time out in ' + countdown + ' seconds!'
      console.log(this.idleState);
    });

    // sets the ping interval to 15 seconds
    keepalive.interval(15);

    keepalive.onPing.subscribe(() => {
      this.lastPing = new Date(); this.idleState = 'No longer idle.';
      // console.log('====hereeoiuio=========eee')
    });

    this.authenticationService.currentUser.subscribe(userLoggedIn => {
      if (userLoggedIn) {
        idle.watch();
        this.timedOut = false;
      } else {
        idle.stop();
      }
    })
  }

  async ngOnInit() {
    this.config = this.configService.config;
    this.subscription = this.configService.configUpdate$.subscribe(config => this.config = config);
    let institute = "institute"
    if (localStorage.getItem('institute'))
      institute = localStorage.getItem('institute');
    // this.router.navigate(['/auth/login', institute]);

  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }

  reset() {
    this.idle.watch();
    // this.idleState = 'Started.';
    this.timedOut = false;
  }

  hideChildModal(): void {
    this.displaySessionTimeOut = false;
  }

  stay() {
    this.displaySessionTimeOut = false;
    this.reset();

  }

  async logout() {
    this.displaySessionTimeOut = false;
    await this.authenticationService.logOut();
    // this.router.navigate(['/']);
    let institute = localStorage.getItem("institute");
    this.router.navigate(['/auth/login', institute]);
  }
  openDialog(): void {
    const dialogRef = this.dialog.open(TimeOutDialogComponent, {
      width: '350px',
      data: { state: this.idleState },
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result.data == 'S')
        this.stay();
      else
        this.logout()
    });
  }

}
function DEFAULT_INTERRUPTSOURCES(DEFAULT_INTERRUPTSOURCES: any) {
  throw new Error('Function not implemented.');
}

