import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { tap } from 'rxjs/operators';
import { RefData } from '../models/ref-data.enum';
import { of } from 'rxjs';
//import 'rxjs/add/observable/of';

@Injectable({
  providedIn: 'root',
})
export class ServiceRefData {
  private cache: Map<RefData, Observable<any>>;

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

  public get<T>(key: RefData, 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));
                        }));
    }
  }
}
