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

interface VoiceWorkspacePlaybackSettings {
  muted: boolean;
  volume: number;
}

const DEFAULT_SETTINGS: VoiceWorkspacePlaybackSettings = {
  muted: false,
  volume: 100
};

@Injectable({ providedIn: 'root' })
export class VoiceWorkspacePlaybackService {
  private readonly _settings = signal<ReadonlyMap<string, VoiceWorkspacePlaybackSettings>>(new Map());

  settings(): ReadonlyMap<string, VoiceWorkspacePlaybackSettings> {
    return this._settings();
  }

  getUserVolume(peerId: string): number {
    return this._settings().get(peerId)?.volume ?? DEFAULT_SETTINGS.volume;
  }

  isUserMuted(peerId: string): boolean {
    return this._settings().get(peerId)?.muted ?? DEFAULT_SETTINGS.muted;
  }

  setUserVolume(peerId: string, volume: number): void {
    const nextVolume = Math.max(0, Math.min(100, volume));
    const current = this._settings().get(peerId) ?? DEFAULT_SETTINGS;

    this._settings.update((settings) => {
      const next = new Map(settings);

      next.set(peerId, {
        ...current,
        muted: nextVolume === 0 ? current.muted : false,
        volume: nextVolume
      });

      return next;
    });
  }

  setUserMuted(peerId: string, muted: boolean): void {
    const current = this._settings().get(peerId) ?? DEFAULT_SETTINGS;

    this._settings.update((settings) => {
      const next = new Map(settings);

      next.set(peerId, {
        ...current,
        muted
      });

      return next;
    });
  }

  resetUser(peerId: string): void {
    this._settings.update((settings) => {
      if (!settings.has(peerId)) {
        return settings;
      }

      const next = new Map(settings);

      next.delete(peerId);
      return next;
    });
  }

  teardownAll(): void {
    // Stream audio is played directly by the video element.
  }
}
