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

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


  searchCrossrefResults(term: string, size: number, page: number, properties: EnvProperties, parse: boolean = false): any {
    let url = properties.searchCrossrefAPIURL + '?query=' + term + '&rows=' + size + '&offset=' + (size * (page - 1));

     return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
                     .pipe(map(request => request['message']))
                     .pipe(map(request => [request["total-results"], parse ? this.parse(request.items) : request]))
                     //.catch(this.handleError);

  }

  searchCrossrefByDOIs(DOIs: string[], properties: EnvProperties, parse: boolean = false, file: boolean = false): any {
    let timeoutTime: number = properties.environment == "production" ? 6000 : 12000;
    // let timeoutTimeForFile: number = 60000;

    var doisParams = "";
    for (var i = 0; i < DOIs.length; i++) {
      doisParams += (doisParams.length > 0 ? "," : "") + 'doi:' + DOIs[i];
    }
    let url = properties.searchCrossrefAPIURL + '?filter=' + doisParams;
           return this.http.get(url)
             // .pipe(timeout(file ? timeoutTimeForFile : (timeoutTime)))
             .pipe(timeout(timeoutTime))
             .pipe(map(request => request['message']))
             .pipe(map(request => [request["total-results"], parse ? this.parse(request['items']) : request]))
}

  searchCrossrefByDOI(DOI: string): any {
    let timeoutTimeForFile: number = 20000;

    let url = properties.searchCrossrefAPIURL + '/' + StringUtils.URIEncode(DOI);
    return this.http.get(url)
      .pipe(timeout(timeoutTimeForFile))
      .pipe(map(request => request['message']))
      .pipe(map(request => this.parse(request)))
  }
  searchCrossrefByMultipleDOIs(dois: string[], properties: EnvProperties, parse: boolean = false): any {
    let url = properties.searchCrossrefAPIURL + '?filter=doi:';
    for (var i = 0; i < dois.length; i++) {
      url = url + (url.length == 0 ? '' : ',') + 'doi:' + dois[i];
    }
    url = properties.searchCrossrefAPIURL + '?filter=' + url;
         return this.http.get(url)
                         //.map(request => <any> request.json().message)
                         .pipe(map(request => request['message']))
                         .pipe(map( request => [request["total-results"], parse ? this.parse(request.items) : request]))
                         //.catch(this.handleError);

  }

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

  parse(response): ClaimEntity[] {
    const results: ClaimEntity[] = [];
    let length = Array.isArray(response) ? response.length : 1;

    for (let i = 0; i < length; i++) {
      const item = Array.isArray(response) ? response[i] : response;

      const entity: ClaimEntity = new ClaimEntity();
      entity.result = new ClaimResult();
      entity.result.publisher = null;
      entity.result.journal = null;
      entity.result.DOI = item.DOI;
      entity.id = item.DOI;
      entity.title = item.title;
      entity.result.url = item.URL;
      entity.result.source = 'crossref';
      entity.type = 'publication';
      if (item['published-print']) {
        entity.result.date = item['published-print']['date-parts'][0][0];
      }
      entity.result.accessRights = "OPEN";
      entity.result.publisher = item.publisher;
      entity.result.journal = null;
      entity.result.record = item;
      if (item.author) {
        entity.result.authors = [];
        for (let j = 0; j < item.author.length; j++) {
          let author = this.parseName(item.author[j]);
          if(author) {
            entity.result.authors.push(author);
          }
        }
      }
      if (item.editor) {
        for (let j = 0; j < item.editor.length; j++) {
          let editor = this.parseName(item.editor[j]);
          if(editor) {
            entity.result.authors.push(editor);
          }
        }
      }
      results.push(entity);
    }

    return results;

  }

  private parseName(authorObj) : string {
    let author: string = "";
    if(authorObj.hasOwnProperty("family")) {
      author += authorObj.family;
    }
    if(authorObj.hasOwnProperty("family") && authorObj.hasOwnProperty("given")) {
      author += ", ";
    }
    if(authorObj.hasOwnProperty("given")) {
      author += authorObj.given;
    }

    if(!author && authorObj.hasOwnProperty("name")) {
      author += authorObj.name;
    }

    return author;
  }

}
