import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import{EnvProperties} from '../../utils/properties/env-properties';
import {map} from "rxjs/operators";

@Injectable()
export class SearchCommunityProjectsService {
    constructor(private http: HttpClient ) {}

    searchProjects (properties:EnvProperties, pid: string, page=1, size=500):any {
        return this.searchProjectsWithPaging(properties,pid,page, size, null, null);
    }
    searchProjectsWithPaging (properties:EnvProperties, pid: string, page=1, size=500, searchFilter, funder, orderBy = "name"):any {
        let params = funder ? ["funder="+ funder] :[];
        if (searchFilter) {
            params.push("searchFilter="+ searchFilter)
        }
        params.push("orderBy="+ orderBy);
        let url = properties.communityAPI+pid+"/projects/"+ (page-1) + "/" + size +  (params.length > 0?"?" + params.join("&"):"");
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url);
    }
    countTotalProjects(properties:EnvProperties,pid:string) {
        let url = properties.communityAPI+pid+"/projects/0/1";
        return  this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
          .pipe(map(res => res['totalElements']));
    }
    getProjectFunders(properties:EnvProperties,pid:string) {
        let url = properties.communityAPI+pid+"/funders";
        return  this.http.get<string[]>((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url);
    }
}
