import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable}     from 'rxjs';
import {Metrics} from '../utils/entities/metrics';

import{EnvProperties} from '../utils/properties/env-properties';
import {map} from "rxjs/operators";

@Injectable({
    providedIn: 'root'
})
export class MetricsService {
    metrics: Metrics;

    constructor(private http: HttpClient ) {}

    hasAltMetrics(url: string, doi: string): Observable<boolean> {
        return this.http.get(url + doi).pipe(map(res => !!(res)));
    }
    getMetricsNumber (id: string, table: string, properties:EnvProperties):any {

        let url =properties.statisticsFrameNewAPIURL + 'raw?json='  + encodeURIComponent('{"series":[{"query":{"name":"' + table + '", "parameters":["' + id + '"], "profile":"OpenAIRE All-inclusive"}}],"verbose":true}');

        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
          .pipe(map(res => this.parseMetricsNumber(res)));
    }
    parseMetricsNumber(res){
        try{
            return +res["datasets"]["0"]["series"]["result"]["0"]["row"]["0"];
        }catch(e){
            return null;
        }

    }
    getMetricsNumbersByRepository (id: string, table: string, properties:EnvProperties):any {

        let url =properties.statisticsFrameNewAPIURL + 'raw?json='  + encodeURIComponent('{"series":[{"query":{"name":"' + table + '", "parameters":["' + id + '","' + id + '","' + id + '"], "profile":"OpenAIRE All-inclusive"}}],"verbose":true}');

        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
          .pipe(map(res => this.parseMetricsNumbersByRepository(res,properties)));
    }
    parseMetricsNumbersByRepository(res,properties){
        let map = new Map<string, {"name": string, "url": string, "numOfDownloads": string, "numOfViews": string, "openaireDownloads": string, "openaireViews": string}>();
        try{

            let results = res["datasets"]["0"]["series"]["result"];
            for(let i=0; i<results.length; i++) {
                let result = results[i]["row"];
                let id: string = result[1];
                if(map.has(id)) {
                    if(result[0] == "views"){
                        map.get(id).numOfViews = result[3];
                        map.get(id).openaireViews = result[4];
                    }else if(result[0] == "downloads") {
                        map.get(id).numOfDownloads = result[3];
                        map.get(id).openaireDownloads = result[4];
                    }
                } else {
                    let info;//: {"url": string, "numOfDownloads": string, "numOfViews": string};
                    info = {};

                    info.name = result[2];
                    info.url = id;
                    info.numOfDownloads = "0";
                    info.openaireDownloads = "0";
                    info.numOfViews = "0";
                    info.openaireViews = "0";
                    if(result[0] == "views"){
                        info.numOfViews = result[3];
                        info.openaireViews = result[4];
                    }else if(result[0] == "downloads") {
                        info.numOfDownloads = result[3];
                        info.openaireDownloads = result[4];
                    }
                    if(info.numOfViews +  info.openaireViews + info.numOfDownloads + info.openaireDownloads > 0) {
                        map.set(id, info);
                    }
                }
            }
        }catch(e){
            console.error(e)
        }
        return map;

    }
    
}
