// timer.service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

const TIMER_KEY = 'admin_session_timer';

@Injectable({
  providedIn: 'root'
})
export class TimerService {
  private timerSubject = new Subject<number>();
  private innertimerSubject = new Subject<number>();
  private timer!: number;
  private innerTimer!: number;
  private timerSubscription: any;
  private innertimerSubscription: any;

  constructor() {
  }
  // For admin
  startTimer(duration: number): void {
    if(duration){
      this.timer = duration;
      this.stopTimer();
      this.timerSubscription = setInterval(() => {
        const storedState = localStorage.getItem(TIMER_KEY);
        if (storedState) {
          const { timer } = JSON.parse(storedState);
          if(timer > this.timer){
            this.stopInnerTimer();
            this.timer = timer;
          }
        }

        this.timerSubject.next(this.timer);
        if (this.timer > 0) {
          this.timer--;
          this.stopInnerTimer();
          this.updateStorage();
        }
      }, 1000);
    }
  }

  startInnerTimer(duration: number): void {
    this.innerTimer = duration;
    this.stopInnerTimer();
    this.innertimerSubscription = setInterval(() => {
      this.innertimerSubject.next(this.innerTimer);
      if (this.innerTimer > 0) {
        this.innerTimer--;
        this.updateStorage();
      }
    }, 1000);
  }

  resetTimer(duration): void {
    this.stopTimer();
    this.stopInnerTimer();
    this.innerTimer = 0;
    this.startTimer(duration); // Reset the timer with the initial value
    this.updateStorage();
  }
  stopTimer(): void {
    clearInterval(this.timerSubscription);
  }
  stopInnerTimer(): void {
    clearInterval(this.innertimerSubscription);
  }


 
  private updateStorage(): void {
    const timerState = { timer: this.timer, innerTimer: this.innerTimer || 60 };
    localStorage.setItem(TIMER_KEY, JSON.stringify(timerState));
  }

  getTimerObservable(): Observable<number> {
    return this.timerSubject.asObservable();
  }
  getInnerTimerObservable(): Observable<number> {
    return this.innertimerSubject.asObservable();
  }

  getSecondaryTimer(): number {
    return this.innerTimer;
  }

  loadStateFromStorage(): void {
    const storedState = localStorage.getItem(TIMER_KEY);
    if (storedState) {
      const { timer, innerTimer } = JSON.parse(storedState);
      this.timer = timer;
      this.innerTimer = innerTimer;
    }
  }
}
