import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse } from '@angular/common/http';

@Injectable()
export class RequestCache {
  private cache: Map<string, any>;

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

  get(req: HttpRequest<any>): HttpResponse<any> | undefined {
    const splittedUrl = req.urlWithParams.split('/');
    const url = splittedUrl[splittedUrl.length - 1] + '_' + req.method;
    this.clearExpiredEntries();
    const cached = this.cache.get(url);

    let cachedResponse: HttpResponse<any>;
    if (cached) {
      cachedResponse = cached.response;
    }

    return cachedResponse;
  }

  put(req: HttpRequest<any>, response: HttpResponse<any>): void {
    const splittedUrl = req.urlWithParams.split('/');
    const url = splittedUrl[splittedUrl.length - 1] + '_' + req.method;

    const entry = { url, response, lastRead: Date.now() };
    this.cache.set(url, entry);
    this.clearExpiredEntries();
  }

  private clearExpiredEntries(): void {
    const maxAge = 30000;
    const expired = Date.now() - maxAge;

    this.cache.forEach(expiredEntry => {
      if (expiredEntry.lastRead < expired) {
        this.cache.delete(expiredEntry.url);
      }
    });
  }
}
