import { Injectable } from '@angular/core';
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
import {StatisticsDisplay, StatisticsSummary} from "../../openaireLibrary/connect/statistics/statisticsEntities";
import {catchError, map} from "rxjs/operators";
import {Observable, throwError} from "rxjs";
import {EnvProperties} from "../../openaireLibrary/utils/properties/env-properties";


@Injectable()
export class StatisticsService {


    constructor(private http:HttpClient) { }

    getCommunityStatistics(properties:EnvProperties, communityId: string): Observable<StatisticsSummary> {
        let url = properties.statisticsAPIURL+"/communities/"+communityId;
        //console.log(`getting statistics summary from: ${url}`);
        return this.http.get<any>((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
            //.map(res => <any>res.json())
            .pipe(map(res => res['statistics']));
    }

    getCommunityAdminStatisticsChoices(properties: EnvProperties, communityId: string): Observable<StatisticsDisplay> {
        let url = properties.adminToolsAPIURL+"/statistics/"+communityId;
        //console.log(`getting admin choices for statistics from: ${url}`);
        return this.http.get<StatisticsDisplay>((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
            //.map(stats => <StatisticsDisplay>stats.json())
            .pipe(catchError(this.handleError));
    }


    private handleError (error: HttpErrorResponse) {
        // in a real world app, we may send the error to some remote logging infrastructure
        // instead of just logging it to the console
        console.log(error);
        return throwError(error  || 'Server error');
    }
}
