import {Injectable}                 from '@angular/core';
import {HttpClient} from "@angular/common/http";

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

@Injectable()
export class ZenodoCommunitiesService {

    constructor(private http:HttpClient) {
    }

    getZenodoCommunities(properties:EnvProperties, url: string) {
            return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)) : url)
                            //.map(res => <any> res.json())
                            .pipe(map(res => [this.parseZenodoCommunities(res['hits'].hits),res['hits'].total]));
    }
    getZenodoCommunityById(properties:EnvProperties, id: string) {
      let url = properties.zenodoCommunities + "/" + id;
            return this.http.get((properties.useLongCache)? (properties.cacheUrl+encodeURIComponent(url)) : url)
                            //.map(res => <any> res.json())
                            .pipe(map(res => {
                              var community = this.parseZenodoCommunity(res);
                              return community;
                            }));
    }

    parseZenodoCommunities(data: any): ZenodoCommunityInfo[] {
        let zenodoCommunities: ZenodoCommunityInfo[] = [];

        for (let i=0; i<data.length; i++) {
            let resData = data[i];


            zenodoCommunities.push(this.parseZenodoCommunity(resData));
        }
        return zenodoCommunities;
    }

    parseZenodoCommunity(resData:any):ZenodoCommunityInfo {
      var result: ZenodoCommunityInfo = new ZenodoCommunityInfo();
      let metadata = resData["metadata"];
      result['title'] = metadata.title;
      result['id'] = resData.id;
      result['description'] = metadata.description;
      result['link'] = resData.links.self_html;
      result['logoUrl'] = resData.links.logo;
      result['date'] = resData.updated;
      result['page'] = metadata.page;
      return result;

    }

    getTotalZenodoCommunities(properties:EnvProperties, url: string) {
            return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)) : url)
                            //.map(res => <any> res.json())
                            .pipe(map(res => res['hits'].total));
    }
}
