import { HttpClient } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { Observable, shareReplay } from 'rxjs';
import { TimezoneListResponse } from '../models/timezone.model';
import { API_URL } from '../tokens/api-url.token';

@Injectable({ providedIn: 'root' })
export class TimezoneApiService {
  private cache$?: Observable<TimezoneListResponse>;

  constructor(
    private http: HttpClient,
    @Inject(API_URL) private apiUrl: string,
  ) {}

  list(): Observable<TimezoneListResponse> {
    if (!this.cache$) {
      this.cache$ = this.http
        .get<TimezoneListResponse>(`${this.apiUrl}/timezones`)
        .pipe(shareReplay(1));
    }
    return this.cache$;
  }
}
