import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {ResultLandingInfo} from '../../../utils/entities/resultLandingInfo';
import {EnvProperties} from '../../../utils/properties/env-properties';
import {ParsingFunctions} from '../../landing-utils/parsingFunctions.class';
import {map} from "rxjs/operators";
import {HostedByCollectedFrom} from "../../../utils/result-preview/result-preview";

@Injectable()
export class DeletedByInferenceService {
  private sizeOfDescription: number = 270;

  constructor(private http: HttpClient ) {
    this.parsingFunctions = new ParsingFunctions();
  }

  public parsingFunctions: ParsingFunctions;

  getDeletedByInferenceResults (id: string, size: string, properties:EnvProperties):any {
    let url = properties.searchAPIURLLAst + 'deletedByInferenceResults/' +id+"?format=json&size="+size;
    let key = url;

    return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
                //.map(res => <any> res.json())
                .pipe(map(res => res['results']))
                .pipe(map(res => this.parseDeletedByInferenceResults(res)));
  }

  parseDeletedByInferenceResults (_results: any): ResultLandingInfo[] {
    /*title, authors, abstract, List of projects, PIDs,
      collectedfrom (link pointing to the download url), access rights*/

    let results: ResultLandingInfo[] = [];
    if(_results) {
      let result : ResultLandingInfo;

      let length = Array.isArray(_results) ? _results.length : 1;
      for(let i=0; i<length; i++) {
        var _result = Array.isArray(_results) ? _results[i]['result']['metadata']['oaf:entity'] : _results['result']['metadata']['oaf:entity'];

        result = new ResultLandingInfo();

        if(_result) {
          if(_result['oaf:result']) {
            let data = _result['oaf:result'];

            var date:string = (data.dateofacceptance)+""; // transform to string in case it is an integer
            result.date  = (date && (date).indexOf('-') !== -1)?date.split('-')[0]:date;
            result.dateofacceptance = data.dateofacceptance;
            result.embargoEndDate = data.embargoenddate;

            result.description = this.parsingFunctions.parseDescription(data.description, true);

            if(data['bestaccessright'] && data['bestaccessright'].hasOwnProperty("classname")) {
              result.accessMode = data['bestaccessright'].classname;
            }
          }

          if(_result['oaf:result'] && _result['oaf:result']['title']) {
            let title = _result['oaf:result']['title'];

            if(Array.isArray(title)) {
              for(let i=0; i<title.length; i++) {
                if(title[i] && title[i].content) {
                  if(!result.title || title[i].classid == "main title") {
                    result.title = String(title[i].content);
                  }
                  if(title[i].classid == "main title") {
                    break;
                  }
                }
              }
              if(!result.title) {
                result.title = "";
              }
              //result.title = title[0].content;
            } else {
              result.title = String(title.content);
            }
          }

          if(_result['oaf:result'] && _result['oaf:result']['language']) {
            result.languages = this.parsingFunctions.parseLanguages(_result['oaf:result']['language']);
          }
          if(_result['oaf:result'] && _result['oaf:result']['country']) {
            result.countries = this.parsingFunctions.parseCountries(_result['oaf:result']['country']);
          }

          if(_result['oaf:result'] && _result['oaf:result']['children']) {
            let children = _result['oaf:result']['children'];

            if(children.hasOwnProperty("instance")) {
              result.types = new Array<string>();
              let types = new Set<string>();

              result.hostedBy_collectedFrom = new Array<HostedByCollectedFrom>();

              let counter = 0;
              let instance;

              let length = Array.isArray(children['instance']) ? children['instance'].length : 1;

              for(let i=0; i<length; i++) {
                instance = Array.isArray(children['instance']) ? children['instance'][i] : children['instance'];

                this.parsingFunctions.parseTypes(result.types, types, instance);

                if(instance.hasOwnProperty("webresource")) {
                  let url;
                  if(!Array.isArray(instance['webresource'])) {
                    url = instance['webresource'].url;
                  } else{
                    url = instance['webresource'][0].url;
                  }

                  if(instance.hasOwnProperty("hostedby")) {
                    this.parsingFunctions.parseHostedBy_collectedFrom(result.hostedBy_collectedFrom, instance, url, result.accessMode);
                  }
                }
              }
            }
          }

          if(_result['oaf:result'] && _result['oaf:result']['pid']) {
            result.identifiers = this.parsingFunctions.parseIdentifiers(_result['oaf:result']['pid']);
          }

          if(_result['oaf:result'] && _result['oaf:result']['creator']) {
            if(result.authors == undefined) {
              result.authors = new Array<{"fullName": string, "orcid": string, "orcid_pending": string}>();
            }

            let authors = _result['oaf:result']['creator'];
            let length = Array.isArray(authors) ? authors.length : 1;

            for(let i=0; i<length; i++) {
              let author = Array.isArray(authors) ? authors[i] : authors;
              if(author) {
                /*if (author.orcid && author.orcid.indexOf(properties.orcidURL) != -1) {
                  author.orcid = author.orcid.substr(properties.orcidURL.length);
                }*/
                if(author.orcid) {
                  author.orcid = author.orcid.toUpperCase();
                }
                if(author.orcid_pending) {
                  author.orcid_pending = author.orcid_pending.toUpperCase();
                }

                if(result['authors'][author.rank] && results['authors'][author.rank].fullName == author.content) {
                  if(!author.orcid && result['authors'][author.rank].orcid) {
                    author.orcid = result['authors'][author.rank].orcid;
                  } else if(!author.orcid_pending && result['authors'][author.rank].orcid_pending) {
                    author.orcid_pending = result['authors'][author.rank].orcid_pending;
                  }
                }

                result['authors'][author.rank] = {"fullName": author.content, "orcid": author.orcid, "orcid_pending": author.orcid_pending};
              }
            }
            result.authors = result.authors.filter(function (item) {
              return (item != undefined && item.fullName != undefined);
            });
          }

        }
        results.push(result);
      }
    }

    return results;
  }
}
