import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {EnvProperties} from './properties/env-properties';
import {BehaviorSubject, Observable, of} from "rxjs";
import {catchError, map} from "rxjs/operators";
import {properties} from "../../../environments/environment";


@Injectable({
  providedIn: "root"
})
export class IndexInfoService {
  private lastIndexDateSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);

  constructor(private http: HttpClient) {
  }

  get lastIndexDate(): Observable<any> {
    return this.lastIndexDateSubject.getValue() ? this.lastIndexDateSubject.asObservable() : this.getLastIndexDate();
  }

  setLastIndexDate(value: any) {
    this.lastIndexDateSubject.next(value);
  }

  getLastIndexDate(props: EnvProperties = properties): Observable<any> {
    let url = props.indexInfoAPI;
    return this.http.get((props.useLongCache)? (props.cacheUrl+encodeURIComponent(url)): url).pipe(map(res => {
      this.setLastIndexDate(res['claim_load_date']);
      return res['claim_load_date'];
    })).pipe(catchError(err => {return of(null)}));
  }
  getStatsLastDate(properties: EnvProperties): Observable<any> {
    let url = properties.indexInfoAPI;
    return this.http.get((properties.useLongCache)? (properties.cacheUrl+encodeURIComponent(url)): url).pipe(map(res => res['stats_update_date'])).pipe(catchError(err => {return of(null)}));
  }
  getLastOrcidUpdateDate(properties: EnvProperties): Observable<any> {
    let url = properties.indexInfoAPI;
    return this.http.get((properties.useLongCache)? (properties.cacheUrl+encodeURIComponent(url)): url).pipe(map(res => res['orcid_update_date'])).pipe(catchError(err => {return of(null)}));
  }
  getDBLoadLastDate(properties: EnvProperties): Observable<any> {
    let url = properties.indexInfoAPI;
    return this.http.get((properties.useLongCache)? (properties.cacheUrl+encodeURIComponent(url)): url).pipe(map(res => res['db_load_date'])).pipe(catchError(err => {return of(null)}));
  }
}



