import { Howl, type HowlOptions } from "howler";

export type HowlLoadOptions = Omit<HowlOptions, "src">;

export const defaultHowlOptions: HowlLoadOptions = {
  volume: 0.5,
  loop: false,
  html5: true,
};

/**
 * HowlManager is a singleton class that manages a single Howl instance.
 */
export default class HowlManager {
  private static instance: HowlManager;
  private howl: Howl | null = null;
  private src: string | string[] | null = null;

  public static getInstance(): HowlManager {
    if (!HowlManager.instance) {
      HowlManager.instance = new HowlManager();
    }
    return HowlManager.instance;
  }

  public load(
    src: string | string[],
    options: HowlLoadOptions = defaultHowlOptions,
  ): Howl {
    if (this.howl && this.src === src) {
      return this.howl;
    }

    if (this.howl) this.destroy();
    this.howl = new Howl({ src, ...options });
    this.src = src;
    return this.howl;
  }

  public play(): void {
    this.howl?.play();
  }

  public pause(): void {
    this.howl?.pause();
  }

  public mute(muted: boolean): void {
    this.howl?.mute(muted);
  }

  public stop(): void {
    this.howl?.stop();
  }

  public destroy(): void {
    this.howl?.unload();
    this.howl = null;
    this.src = null;
  }
}
