import { HttpClient, HttpHandler, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { CacheService } from '@shared/services/cache.service';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable({
    providedIn: 'root',
})
export class ApiService extends HttpClient {
    constructor(handler: HttpHandler, private cache: CacheService) {
        super(handler);
    }

    cacheFirst<T>(url: string, params: HttpParams) {
        const options = params.toString();
        const key = `${url}?${options}`
        const cached = this.cache.get(key, options);

        if (cached) {
            return Promise.resolve(cached);
        }

        return this.get<T>(url, { params })
            .toPromise()
            .then((result) => {
                this.cache.set(key, options, result);

                return result;
            });
    }
    
    cacheFirst$<T>(url: string, params: HttpParams): Observable<T> {
        const options = params.toString();
        const key = `${url}?${options}`
        const cached = this.cache.get(key, options);

        if (cached) {
            return of(cached as T);
        }

        return this.get<T>(url, { params }).pipe(
            tap(result => this.cache.set(key, options, result))
        );
  }

}
