import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
import {throwError} from 'rxjs';


import { CustomOptions } from '../../services/servicesUtils/customOptions.class';
import {catchError} from "rxjs/operators";

@Injectable()
export class ClaimsByTokenService {

    constructor(private http: HttpClient ) {}

    getClaims(openaireId: string,  apiURL:string):any {

        //let url = apiURL+"project/claims?projectToken="+token;
        let url = apiURL+"projects/"+openaireId+"/all_claims";

        let key = url;

        return this.http.get(url, CustomOptions.getAuthOptionsWithBody());


    }



  updateClaimsCuration( selectedRight: Set<string>, selectedWrong: Set<string>, apiURL:string) {
    let url = apiURL + "curate/bulk";
    let claimsCurationInfo: any = []; //e.g.:  [{"id":"2","approved":true},{"id":"1","approved":true}]

    selectedRight.forEach(function(selected) {
      //console.info(selected);
      let claimCurationInfo: {"id": string, "approved": boolean} = {"id": selected, "approved": true};
      claimsCurationInfo.push(claimCurationInfo);
    });

    selectedWrong.forEach(function(selected) {
      let claimCurationInfo: any = {"id": selected, "approved": false};
      claimsCurationInfo.push(claimCurationInfo);
    });


    let body = JSON.stringify( claimsCurationInfo );
    //console.warn('Json body:  : '+body);

    return this.http.post(url, body,  CustomOptions.getAuthOptionsWithBody())
                          //.map(res => res.json())
                          //.do(request => console.info("Insert Response:"+request.status) )
                          .pipe(catchError(this.handleError));
  }


    updateClaimCuration( claimCurationInfo: {"id": string, "approved": boolean}, apiURL:string) {
      let url = apiURL + "curate/bulk";
      let claimsCurationInfo: any = []; //e.g.:  [{"id":"2","approved":true},{"id":"1","approved":true}]
      claimsCurationInfo.push(claimCurationInfo);


      let body = JSON.stringify( claimsCurationInfo );
      //console.warn('Json body:  : '+body);

      return this.http.post(url, body,  CustomOptions.getAuthOptionsWithBody())
                            //.map(res => res.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');
    //return Observable.throw(error  || 'Server error');
  }
}
