import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";
import { CacheApiKey } from "../models/cache-api-key.enum";
import { of } from "rxjs";

@Injectable({ providedIn: "root" })
export class ServiceCacheApi {
  private cache: Map<CacheApiKey, Observable<any>>;

  constructor() {
    this.cache = new Map<CacheApiKey, Observable<any>>();
  }

  public get<T>(key: CacheApiKey, callToApi: Observable<T>): Observable<T> {
    const cached = this.cache.get(key);

    if (cached) {
      return cached;
    } else {
      return callToApi.pipe(
        tap((event) => {
          this.cache.set(key, of(event));
        })
      );
    }
  }

  public delete(key: CacheApiKey) {
    this.cache.delete(key);
  }

  public getByKey<T>(key: CacheApiKey): Observable<T> {
    return this.cache.get(key);
  }
}
