export interface ObjectUrlApi {
  createObjectURL(blob: Blob): string;
  revokeObjectURL(url: string): void;
}

export class ObjectUrlRegistry {
  readonly #api: ObjectUrlApi;
  readonly #urls = new Map<string, string>();

  constructor(api: ObjectUrlApi = URL) {
    this.#api = api;
  }

  replace(key: string, blob: Blob): string {
    this.revoke(key);
    const url = this.#api.createObjectURL(blob);
    this.#urls.set(key, url);
    return url;
  }

  get(key: string): string | undefined {
    return this.#urls.get(key);
  }

  revoke(key: string): boolean {
    const url = this.#urls.get(key);
    if (!url) {
      return false;
    }
    this.#api.revokeObjectURL(url);
    this.#urls.delete(key);
    return true;
  }

  clear(): void {
    for (const url of this.#urls.values()) {
      this.#api.revokeObjectURL(url);
    }
    this.#urls.clear();
  }

  get size(): number {
    return this.#urls.size;
  }
}
