import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {CountryUsageStat, UsageStat} from '../entities/usage-stat';
import {Observable} from 'rxjs';
import {properties} from '../../environments/environment';
import {map} from 'rxjs/operators';

@Injectable({
  providedIn: "root"
})
export class UsageStatsService {
  
  constructor(private http: HttpClient) {}
  
  
  getAllMetrics(): Observable<UsageStat> {
    let url = properties.metricsAPIURL + 'allmetrics';
    return this.http.get<UsageStat>((properties.useLongCache?(properties.cacheUrl + encodeURIComponent(url)):url));
  }
  
  getCountryMetrics(country: string): Observable<CountryUsageStat> {
    let url = properties.metricsAPIURL + 'countryusagestats/' + country;
    return this.http.get<CountryUsageStat>((properties.useLongCache?(properties.cacheUrl + encodeURIComponent(url)):url)).pipe(map(stat => {
      if(stat.total_repos == "0" && !stat.views && !stat.downloads) {
        return null;
      } else {
        return stat;
      }
    }));
  }
}
