import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class AlarmSoundService {
  private alertInterval: any;
  private alertDuration: number = 10000;
  private audio = new Audio();
  private isPlaying: boolean = false;

  constructor() {
    this.audio.src = 'assets/sound/alarm_5m.mp3';
    this.audio.load();
    this.audio.onended = () => {
      // Khi phát hết âm thanh, đặt biến isPlaying về false
      this.isPlaying = false;
    };
  }

  playSound(): void {
    if (!this.isPlaying) {
      this.audio.play().then(() => {
        this.isPlaying = true;
        this.alertInterval = setInterval(() => {
          this.stopAlarm();
        }, this.alertDuration);
      }).catch((error) => {
        console.error('Error playing audio:', error);
      });
    }
  }

  stopSound(): void {
    if (this.audio) {
      this.audio.pause();
      this.audio.currentTime = 0;
      this.isPlaying = false;
    }
  }

  startAlarm( isTurnOn: boolean, isReady: boolean, fireArm: boolean, fenceArm: boolean): void {
    if (isTurnOn && isReady && (fireArm || fenceArm)) {
      this.playSound();
    }
  }

  stopAlarm(): void {
    this.stopSound();
    clearInterval(this.alertInterval);
  }

}
