import { Injectable, inject } from '@angular/core'
import { UserIdleService } from 'angular-user-idle';

import { AuthenticationService } from "../providers/user/authentication.service"

@Injectable({ providedIn: 'root' })
export class IdleMonitorService
{
  private readonly idleService = inject(UserIdleService);
  private readonly authSvc = inject(AuthenticationService);

  public startMonitor(): void
  {
    if (this.authSvc?.currentUserValue?.idleTime && this.authSvc?.currentUserValue?.timeoutTime && this.authSvc?.currentUserValue?.pingTime)
    {
      //Seting timeouts
      this.idleService.stopWatching();
      this.idleService.setConfigValues({ idle: this.authSvc.currentUserValue.idleTime, timeout: this.authSvc.currentUserValue.timeoutTime, ping: this.authSvc.currentUserValue.pingTime })

      //Start watching for user inactivity.
      this.idleService.startWatching();

      //Start watching when user idle is starting.
      this.idleService.onTimerStart().subscribe(() => { });

      //Stop watch when time is up.
      this.idleService.onTimeout().subscribe(() =>
      {
        this.stopMonitor();
        this.authSvc.logout()?.subscribe(
          {
            next: () => { this.authSvc.loggedout(); },
            error: () => { this.authSvc.loggedout(); }
          });
      });
    }
  }

  public stopMonitor(): void
  {
    if (this.authSvc?.currentUserValue?.id)
    {
      this.idleService.stopTimer();
      this.idleService.stopWatching();
    }
  }
}
