// idle.service.ts
import { Injectable, NgZone,TemplateRef,ViewChild , EventEmitter} from '@angular/core';
import { fromEvent, merge, Observable, of, timer } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';
import { LogoutService } from './logout/logout.service';
import { Router } from '@angular/router';
import {  BsModalService, BsModalRef, ModalOptions } from 'ngx-bootstrap/modal';
@Injectable({
  providedIn: 'root'
})
export class IdleService {
    @ViewChild("pendinglotinfoTemplate", { static: true })
    pendinglotinfoTemplate: TemplateRef<any>;
 //  private idleTime: number = 5000; // 5 seonds in milliseconds
   //private idleTime: number = 10000; // 10 sec in milliseconds

  //private idleTime: number = 600000; // 10 minutes in milliseconds
   private idleTime: number =900000; // 15 minutes in milliseconds
      //private idleTime: number = 1.2e+6; // 20 minutes in milliseconds

  private userActivityEvents: Observable<Event>;
  private sessionStarted: boolean = false;

  config: ModalOptions = {
    backdrop: "static",
    keyboard: false,
    animated: true,
    class: "modal-dialog-centered",
    ignoreBackdropClick: true,
  };
  pendinglotinfoModalRef: BsModalRef;
  pendinglot:number=0;
  assignlot:number=0;
  userid = localStorage.getItem('userid');
  onIdleTimeout: EventEmitter<void> = new EventEmitter<void>(); // EventEmitter to notify the component
  constructor(private ngZone: NgZone
    ,private logoutservices: LogoutService, private router: Router,
    private modalService: BsModalService,) {
    this.userActivityEvents = merge(
      fromEvent(window, 'mousemove'),
      fromEvent(window, 'mousedown'),
      fromEvent(window, 'click'),
      fromEvent(window, 'scroll'),
      fromEvent(window, 'keypress')
    );
  }

  startMonitoring() {
    this.ngZone.runOutsideAngular(() => {
      this.userActivityEvents.pipe(
        tap(() => {
          if (!this.sessionStarted) {
            this.ngZone.run(() => {
              this.handleSessionStart();
            });
          }
        }),
        switchMap(() => {
          //console.log('User activity detected. Resetting timer.');
          // Reset the timer on user activity
          
          return timer(this.idleTime);
        })
      ).subscribe(() => {
        this.ngZone.run(() => {
         // console.log('User has been idle for 10 minutes.');
          this.handleIdleTimeout();
        });
      });
    });
  }
  

  private handleSessionStart() {
    this.sessionStarted = true;
    //console.log('Session started.');
    // Handle session start logic here
  }
  
  private handleIdleTimeout() {
    this.sessionStarted = false;
   // console.log('Session ended due to inactivity.');
       // Handle session end logic here
   this.onIdleTimeout.emit();

  }
   handleTabClose() {
    debugger
    const logid = localStorage.getItem("logid");
  this.logoutservices.logout(logid).toPromise().then(
      (res) => {
        localStorage.setItem('signoff_status','0');
          localStorage.removeItem("LoggedIn");
          localStorage.clear();
          sessionStorage.clear();
          this.router.navigate(['/login']);
      },
      (error) => {
      }
    );
  } 

}

