import {of, throwError as observableThrowError} from 'rxjs';
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {EnvProperties} from '../../../utils/properties/env-properties';
import {ClaimEntity, ClaimResult} from '../claimHelper.class';
import {catchError, map, timeout} from 'rxjs/operators';
import {properties} from "../../../../../environments/environment";


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

  searchDataciteResults(term: string, size: number, page: number, properties: EnvProperties, parse: boolean = false): any {
    //console.info("In search datacite results "+term+ " "+properties.searchDataciteAPIURL);
    let url = properties.searchDataciteAPIURL + '?query=' + term + '&page[size]=' + size + '&page[number]=' + page;
    let key = url;

    return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
      .pipe(map(request => [request["meta"]["total"], (parse ? SearchDataciteService.parse(request["data"]) : request)]));
    //.catch(this.handleError);
  }

  getDataciteResultByDOI(doi: string, properties: EnvProperties, parse: boolean = false, file: boolean = false): any {
    let timeoutTime: number = properties.environment == "production" ? 6000 : 12000;
    let timeoutTimeForFile: number = 20000;

    let url = properties.searchDataciteAPIURL + '/' + doi;
    let key = url;
    return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
      .pipe(timeout(file ? timeoutTimeForFile : (timeoutTime)))
      .pipe(map(request =>  (parse ? SearchDataciteService.parse([request["data"]])[0] : request)), catchError(err => of(null)));
  }


  private handleError(error: Response) {
    // 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 observableThrowError(error  || 'Server error');
  }

  private extractData(res: any) {
    if (res.status < 200 || res.status >= 300) {
      throw new Error('Bad response status: ' + res.status);
    }
    let body = res.json();
    return body.data || {};
  }

  static parse(response): ClaimEntity[] {
    const results: ClaimEntity[] = [];
    for (let i = 0; i < response.length; i++) {
      const item = response[i];
      const entity: ClaimEntity = new ClaimEntity();
      entity.result = new ClaimResult();
      entity.result.publisher = null;
      entity.result.journal = null;
      entity.result.DOI = item.attributes.doi;
      entity.id = item.attributes.doi;
      entity.title = Array.isArray(item.attributes.titles) && item.attributes.titles[0].title?item.attributes.titles[0].title:null;
      entity.result.url = properties.doiURL + item.attributes.doi;
      entity.result.source = 'datacite';
      entity.type = 'dataset';
      entity.result.date = item.attributes.publicationYear;
      entity.result.accessRights = "OPEN";
      entity.result.publisher = item.attributes['publisher'];
      entity.result.journal = null;
      entity.result.record = item;
      if (item.attributes.creators) {
        entity.result.authors = [];
        for (let j = 0; j < item.attributes.creators.length; j++) {
          const author = item.attributes.creators[j].name;
            entity.result.authors.push(author);
        }
      }
      results.push(entity);
    }

    return results;

  }
}
