import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';
import {ContentProvider} from '../openaireLibrary/utils/entities/contentProvider';
import {Observable} from 'rxjs/Observable';

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

  removeContentProvider(properties: EnvProperties, pid: string, id: string): any {
    let headers = new HttpHeaders({'Content-Type': 'application/json', 'accept': 'application/json'});
    let url = properties.communityAPI + pid + '/contentproviders';
    return this.http.request('delete', url, {body: id, headers: headers});
  }

  addContentProvider(properties: EnvProperties, pid: string, contentProvider: any): Observable<ContentProvider> {
    let url = properties.communityAPI + pid + '/contentproviders';
    let communityContentProvider = this.convertSearchContentProviderToCommunityContentProvider(contentProvider, pid);
    return this.http.post<ContentProvider>(url, communityContentProvider);
  }

  saveContentProvider(properties: EnvProperties, contentProvider: ContentProvider): Observable<ContentProvider> {
    let url = properties.communityAPI + contentProvider.communityId + '/contentproviders';
    return this.http.post<ContentProvider>(url, contentProvider);
  }

  convertSearchContentProviderToCommunityContentProvider(contentProvider: any, community: string): ContentProvider {
    let communityContentProvider: ContentProvider = new ContentProvider();
    communityContentProvider.communityId = community;
    communityContentProvider.officialname = contentProvider.title.name;
    communityContentProvider.name = contentProvider.englishname;
    communityContentProvider.openaireId = contentProvider.id;

    return communityContentProvider;
  }

}
