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



import {map, tap, timeout} from "rxjs/operators";

@Injectable()
export class ReportsService {
    // url:string = "http://beta.services.openaire.eu:8480/search/rest/v2/api/publications?format=csv&page=0&size=3&q=(%22test%22)&fq=instancetypename%20exact%20%22Dataset%22";
    constructor(private http: HttpClient) {}

    //On the service:
   downloadCSVFile(url: string){
     return this.http.get(url, {responseType: 'text'}).pipe(map(res => new Blob([res], { type: 'text/csv' })));
   }
   
   getCSVResponse(url: string){
     return this.http.get(url, {responseType: 'text'})
   }

  /**
   * @deprecated not used
   */
   downloadHTMLFile(url: string, info: string){
     //var headers = new Headers();
     //headers.append('responseType', 'arraybuffer');
     return this.http.get(url)
                .pipe(map(res => this.addInfo(res, info)))
                .pipe(map(res => new Blob([res['_body']], { type: 'text/html' })))
                .pipe(tap(res => console.log(res)))
   }

  /**
   * @deprecated not used
   */
   addInfo(res:any, info:string) {
       /*
       var para = res.document.createElement("P");                       // Create a <p> element
       var t = res.document.createTextNode("This is a paragraph");       // Create a text node
       para.appendChild(t);                                          // Append the text to <p>
       res.document.body.appendChild(para);
       */
       res['_body'] = info+res['_body'];
       return res;
   }

    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');
    }


}
