import { Injectable } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';
import { Observable, ReplaySubject, Subscription, timer } from 'rxjs';
import { catchError, take } from 'rxjs/operators';
import { IItem } from '../models/item';
import { ItemService } from './item.service';

const REFRESH_INTERVAL = 15 * 60 * 1000;  // 15m

@Injectable({ providedIn: 'root'})
export class CacheService {
  private proxyCacheMap: { [key: string]: ReplaySubject<IItem[]> } = {};
  private subscriptionMap: { [key: string]: Subscription } = {};

  constructor(private itemService: ItemService, public oauthService: OAuthService) {
    timer(0, REFRESH_INTERVAL).subscribe(() => {
      this.subscriptionMap = {};
    })
  }

  getItemList(itemType: string) : Observable<IItem[]> {
    if (!this.proxyCacheMap[itemType]) {
      this.proxyCacheMap[itemType] = new ReplaySubject(1);
    }

    if (this.oauthService.getAccessToken() != null && !this.subscriptionMap[itemType]) {
      this.subscriptionMap[itemType] = this.itemService.getItemList(itemType)
        .pipe(          
          catchError(error => {
            this.subscriptionMap[itemType].unsubscribe();
            this.subscriptionMap[itemType] = null;
            throw error;
          }),

      ).subscribe(items => {
        this.proxyCacheMap[itemType].next(items);
      });
    }

    return this.proxyCacheMap[itemType].asObservable()
      .pipe(
        take(1)
      );
  }
}
