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

@Injectable({providedIn: 'root'})
export class NotificationService {

  private readonly notificationSound = new Audio('/public/sounds/notification.mp3');
  private readonly notificationStorageKey = 'chat-notifications-enabled';
  private readonly _notificationEnabled = signal<Record<string, boolean>>(
    this.getStoredNotificationSettings()
  );

  public notify(channel: string) {
    if (!this.isNotificationEnabled(channel)) {
      return;
    }
    this.playSound();

  }

  private enableSound() {
    this.notificationSound.muted = true;
    this.notificationSound.play()
      .then(() => {
        this.notificationSound.pause();
        this.notificationSound.currentTime = 0;
        this.notificationSound.muted = false;
      })
      .catch((error) => {
        console.log('Could not unlock notification sound:', error);
        this.notificationSound.muted = false;
      });
  }

  private playSound() {
    this.notificationSound.currentTime = 0;
    this.notificationSound.play().catch((error) => {
      console.log('Could not play notification sound:', error);
    });
  }

  public isNotificationEnabled(channel: string): boolean {
    return this._notificationEnabled()[channel];
  }

  public enableNotifications(channel: string) {
    this.setNotificationEnabled(channel, true);
    this.enableSound()
  }

  public disableNotifications(channel: string) {
    this.setNotificationEnabled(channel, false);
  }

  private setNotificationEnabled(channel: string, enabled: boolean) {
    const notificationSettings = {
      ...this._notificationEnabled(),
      [channel]: enabled
    };

    this._notificationEnabled.set(notificationSettings);
    localStorage.setItem(this.notificationStorageKey, JSON.stringify(notificationSettings));
  }

  private getStoredNotificationSettings(): Record<string, boolean> {
    const storedSettings = localStorage.getItem(this.notificationStorageKey);

    if (storedSettings === null) {
      return {};
    }

    if (storedSettings === 'true' || storedSettings === 'false') {
      return {};
    }

    try {
      return JSON.parse(storedSettings) as Record<string, boolean>;
    } catch {
      return {};
    }
  }
}
