import {Component, Input} from '@angular/core';
import {SearchCrossrefService} from './service/searchCrossref.service';
import {SearchOrcidService} from './service/searchOrcid.service';
import {SearchResearchResultsService} from '../../services/searchResearchResults.service';
import {SearchDataciteService} from './service/searchDatacite.service';
import {ErrorCodes} from '../../utils/properties/errorCodes';
import {ClaimEntity, ClaimResult} from './claimHelper.class';
import {DOI, StringUtils} from '../../utils/string-utils.class';
import {EnvProperties} from '../../utils/properties/env-properties';
import {Filter, Value} from "../../searchPages/searchUtils/searchHelperClasses.class";
import {forkJoin, Observable, Subscriber} from 'rxjs';
import {NewSearchPageComponent} from "../../searchPages/searchUtils/newSearchPage.component";
import {RangeFilter} from "../../utils/rangeFilter/rangeFilterHelperClasses.class";
import {OpenaireEntities, SearchFields} from "../../utils/properties/searchFields";
@Component({
  selector: 'claim-result-search-form',
  templateUrl: 'claimResultSearchForm.component.html',

})
export class ClaimResultSearchFormComponent {
  page: number = 1;
  size: number = 5;
  source: string = "datacite";
  type: string = "dataset";
  showSearchResults: boolean = false;
  @Input() public centerAlign: boolean = false;
  @Input() public select: boolean = true;
  @Input() public keyword: string = '';
  @Input() public selectedResults: ClaimEntity[];
  @Input() public properties: EnvProperties;
  @Input() localStoragePrefix: string = "";
  @Input() basketLimit;
  @Input() showOptions;
  openaireEntities = OpenaireEntities;
  public errorCodes: ErrorCodes = new ErrorCodes();

  dataciteResults: ClaimEntity[] = [];
  dataciteResultsNum: number = null;
  dataciteStatus = this.errorCodes.NONE;
  datacitePage: number = 1;

  public warningMessage = "";
  public infoMessage = "";

  public todayDate = '';
  public nextDate = '';
  public DOIs: string[] = [];
  sub: any;
  public activeTab: string = "openaire";


  crossrefResults: ClaimEntity[] = [];
  crossrefResultsNum: number = null;
  crossrefPage: number = 1;
  crossrefStatus: number = this.errorCodes.NONE;

  openaireTypeValues = [
    {title: "Publications", value: "publication", count: null},
    {title: "Research Data", value: "dataset", count: null},
    {title: "Software", value: "software", count: null},
    {title: "Other research products", value: "other", count: null}];
  totalOpenaireCount:number = 0;
  openaireResultsfilters = [];
  openaireResultsPrevFilters = [];
  openaireYear = "";

  // public openaireRefineFields: string[] = ["relfunder",  "relproject", "resultbestaccessright", "instancetypename", "resultlanguagename", "community"];
  // public openaireRefineFieldsQuery: string = "&refine=true&fields=relfunder&fields=relproject&fields=resultacceptanceyear&fields=resultbestaccessright&fields=instancetypename&fields=resultlanguagename&fields=community";
  public openaireRefineFields: string[] = ["resulttypeid","relfunder",   "resultbestaccessright", "instancetypename"];
  public openaireRefineFieldsQuery: string = "&refine=true&fields=resulttypeid&fields=relfunder&fields=resultbestaccessright&fields=instancetypename";

  // public fieldIdsMap=this.searchFields.RESULT_FIELDS;
  openaireResults: ClaimEntity[] = [];
  openaireResultsNum: number;
  openaireResultsPage: number = 1;
  openaireResultsStatus: number = this.errorCodes.NONE;
  // openaireResultsType = "publication";

  orcidResults: ClaimEntity[];
  orcidResultsNum: number;
  totalPages: number;
  orcidResultsToShow: ClaimEntity[];
  orcidPage: number = 1;
  orcidStatus: number = this.errorCodes.NONE;
  authorId: string;
  selectAuthorId: string = "0";
  authorGivenName: string;
  authorFamilyName: string;

  authorIds: string[];
  authors = [];

  reloadOpenaire: boolean = true;
  reloadCrossref: boolean = false;
  reloadDatacite: boolean = false;
  reloadOrcid: boolean = false;

  //new search
  quickFilter: { filter: Filter, selected: boolean, filterId: string, value: string } = {
    filter: null,
    selected: true,
    filterId: "resultbestaccessright",
    value: "Open Access"
  };

  resultTypes = {publication: true, dataset: true, software: true, other: true};
  public rangeFilters: RangeFilter[] = [];
  public searchFields: SearchFields = new SearchFields();
  public rangeFields:string[][] = this.searchFields.RESULT_RANGE_FIELDS;
  constructor(private _searchDataciteService: SearchDataciteService,
              private _searchCrossrefService: SearchCrossrefService,
              private _searchOrcidService: SearchOrcidService,
              private _searchResearchResultsService: SearchResearchResultsService) {
    const myDate = new Date();
    this.todayDate = myDate.getFullYear() + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate();
    this.nextDate = (myDate.getFullYear() + 100) + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate();
    this.rangeFilters = RangeFilter.parse(this.rangeFields,"result");
  }

  ngOnInit() {
    if (this.keyword != null && this.keyword.length > 0) {
      this.search(false);
    }
  }
  subscriptions = [];
  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
  }
  search(keywordChanged) {
    //uncomment to disable search with no keyword
    if (this.keyword.length == 0) {
      this.totalOpenaireCount = 0;
      this.crossrefResultsNum = null;
      this.dataciteResultsNum = null;
      this.openaireResultsNum = null;
      this.orcidResultsNum = null;
      this.openaireResults = [];
      this.crossrefResults = [];
      this.dataciteResults = [];
      this.orcidResultsToShow = [];
      this.showSearchResults = false;
      return;
    }
    this.warningMessage = "";
    this.infoMessage = "";
    this.showSearchResults = false;
    if (keywordChanged) {
      // this.activeTab = "openaire";
      this.DOIs = DOI.getDOIsFromString(this.keyword);
      this.reloadOpenaire = true;
      this.reloadCrossref = true;
      this.reloadDatacite = true;
      this.reloadOrcid = true;
      this.crossrefResultsNum = null;
      this.dataciteResultsNum = null;
      this.openaireResultsNum = null;
      this.orcidResultsNum = null;
      // this.openaireResultsType = "publication";
    }

    if (this.reloadOpenaire) {
      this.openaireResults = [];
      this.searchOpenaire(this.keyword, this.size, 1, keywordChanged);
      this.reloadOpenaire = false;
    }
    if (this.reloadCrossref) {
      this.crossrefResults = [];
      this.getCrossrefResults(this.keyword, this.size, 1);
      this.reloadCrossref = false;
    }
    if (this.reloadDatacite) {
      this.dataciteResults = [];
      this.searchDatacite(this.keyword, this.size, 1);
      this.reloadDatacite = false;
    }
    if (this.reloadOrcid) {
      this.orcidResultsToShow = [];
      this.searchOrcid(this.keyword);
      this.reloadOrcid = false;
    }
    this.showSearchResults = true;

  }

  searchOpenaire(keyword, size, page, keywordChanged) {
    this.searchResearchResults("publication", keyword, size, page, true, "publication");
  }

  private getCrossrefResults(term: string, size: number, page: number) {
    this.crossrefStatus = this.errorCodes.LOADING;
    // this.crossrefResultsNum = null;
    if (this.DOIs.length > 0) {
      this.subscriptions.push(this._searchCrossrefService.searchCrossrefByDOIs(this.DOIs, this.properties, true).subscribe(
        data => {
          if (data != null) {
            this.crossrefResults = data[1];
            this.crossrefPage = page;
            this.crossrefResultsNum = data[0];
            if (this.crossrefResultsNum == 0) {
              this.subscriptions.push(this._searchCrossrefService.searchCrossrefResults(StringUtils.URIEncode(term), size, page, this.properties, true).subscribe(
                data => {
                  if (data != null) {
                    this.crossrefResults = data[1];
                    this.crossrefPage = page;
                    this.crossrefResultsNum = data[0];
                    this.crossrefStatus = this.errorCodes.DONE;
                    // console.log("Crossref " + this.crossrefResultsNum);
                    if (this.crossrefResultsNum == 0) {
                      this.crossrefStatus = this.errorCodes.NONE;
                    }

                  } else {
                    this.crossrefStatus = this.errorCodes.ERROR;
                  }
                },
                err => {
                  //console.log(err.status);
                  ClaimResultSearchFormComponent.handleError("Error getting crossref results for term: " + term, err);
                  this.crossrefStatus = this.errorCodes.ERROR;
                }
              ));
            } else {
              this.crossrefStatus = this.errorCodes.DONE;
            }
          }
        },
        err => {
          ClaimResultSearchFormComponent.handleError("Error getting crossref by DOIs: " + JSON.stringify(this.DOIs), err);

          this.subscriptions.push(this._searchCrossrefService.searchCrossrefResults(StringUtils.URIEncode(term), size, page, this.properties, true).subscribe(
            data => {
              this.crossrefResults = data[1];
              this.crossrefPage = page;
              this.crossrefResultsNum = data[0];
              this.crossrefStatus = this.errorCodes.DONE;

            },
            err => {
              //console.log(err.status);
              ClaimResultSearchFormComponent.handleError("Error getting crossref results for term: " + term, err);
              this.crossrefStatus = this.errorCodes.ERROR;
            }
          ));
        }
      ));

    } else {


      this.subscriptions.push(this._searchCrossrefService.searchCrossrefResults(StringUtils.URIEncode(term), size, page, this.properties, true).subscribe(
        data => {
          if (data != null) {
            this.crossrefResults = data[1];
            this.crossrefPage = page;
            this.crossrefResultsNum = data[0];
            this.crossrefStatus = this.errorCodes.DONE;
            if (this.crossrefResultsNum == 0) {
              this.crossrefStatus = this.errorCodes.NONE;
            }
          } else {
            this.crossrefStatus = this.errorCodes.ERROR;
          }

        },
        err => {
          //console.log(err.status);
          ClaimResultSearchFormComponent.handleError("Error getting crossref results for term: " + term, err);
          this.crossrefStatus = this.errorCodes.ERROR;
        }
      ));
    }
  }

  /*private callOpenaireService(term: string, size: number, page: number, mainResults: boolean, type) {
    if (mainResults) {
      this.openaireResultsStatus = this.errorCodes.LOADING;
      this.openaireResultsPrevFilters = this.openaireResultsfilters;
    }
    if((mainResults && page==1 )||!mainResults){
      this.setOpenaireResultsCount(type, null);
      this.totalOpenaireCount = 0;
    }
    if (type == "dataset") {
      this.searchResearchResults("dataset", term, size, page, mainResults, type);
    } else if (type == "software") {
      this.searchResearchResults("software", term, size, page, mainResults, type);
    } else if (type == "other") {
      this.searchResearchResults("other", term, size, page, mainResults, type);
    } else {
      this.searchResearchResults("publication", term, size, page, mainResults, type);
    }


  }*/

  public searchResearchResults(resultType: string, term: string, size: number, page: number, mainResults: boolean, type) {
    this.openaireResultsStatus = this.errorCodes.LOADING;
    this.openaireResultsPrevFilters = this.openaireResultsfilters;
    this.openaireResultsNum = 0;
    this.subscriptions.push(this._searchResearchResultsService.advancedSearchResults('publication', this.createOpenaireQueryParams(), page, size, null, this.properties, this.createOpenaireRefineQueryParams(),  (page==1 ?this.openaireRefineFields:[]), (page==1 ?this.openaireRefineFieldsQuery:null)).subscribe(
      data => {
        this.setOpenaireResults(data, mainResults, page, type);
      },
      err => {
        this.setOpenaireResultsError(mainResults, term, err);
      }
    ));
  }

  public setOpenaireResults(data, mainResults: boolean, page, type) {
    if (data != null) {

        this.openaireResultsPage = page;
        this.openaireResultsNum = data[0];
        // this.setOpenaireResultsCount(type, this.openaireResultsNum);
        if(data[2] && data[2].length > 0){
          this.openaireResultsfilters =  this.checkSelectedFilters(data[2], this.openaireResultsPrevFilters)
        }
        this.openaireResults = ClaimResultSearchFormComponent.openaire2ClaimResults(data[1], this.properties);
        this.openaireResultsStatus = this.errorCodes.DONE;
        if (this.openaireResultsNum == 0) {
          this.openaireResultsStatus = this.errorCodes.NONE;
        }
    } else {
      if (mainResults) {
        this.openaireResultsStatus = this.errorCodes.ERROR;
      }
    }
  }

  public setOpenaireResultsError(mainResults: boolean, term, err) {
    if (mainResults) {
      this.openaireResultsStatus = this.errorCodes.ERROR;
    }
    ClaimResultSearchFormComponent.handleError("Error getting publications for term: " + term, err);
  }

  setOpenaireResultsCount(type, count) {
    if (type == "dataset") {
      this.openaireTypeValues[1]['count'] = count;
    } else if (type == "software") {
      this.openaireTypeValues[2]['count'] = count;
    } else if (type == "other") {
      this.openaireTypeValues[3]['count'] = count;
    } else {
      this.openaireTypeValues[0]['count'] = count;
    }

  }

  private searchOrcid(term: string) {
    if (this.DOIs.length > 0 || term.length == 0) {
      this.orcidStatus = this.errorCodes.NONE;
      this.orcidResultsNum = -1;
      return;
    }
    this.orcidStatus = this.errorCodes.LOADING;
    this.authorIds = new Array<string>();
    this.authors = [];

    this.getOrcidAuthor(term, true);

  }

  /*private readData(data: any) {
    this.authorIds.push(data[2].path);
    var author = {};
    author['id'] = data[2].path;
    if (data[0] != null) {
      author['authorGivenName'] = data[0].value;
    } else {
      author['authorGivenName'] = "";
    }
    if (data[1] != null) {
      author['authorFamilyName'] = data[1].value;
    } else {
      author['authorFamilyName'] = "";
    }
    this.authors.push(author);
  }*/

  private getOrcidAuthor(term: string, addId) {
    this.orcidResultsNum = null;
    //passing structures in order to fill them in service
    this.subscriptions.push(this._searchOrcidService.searchOrcidAuthor(StringUtils.URIEncode(term.replace(/\s/g, "")), this.authorIds,
      this.authors, this.properties, addId).subscribe(
      data => {
        if (data != null && data == true && addId) {
          this.getOrcidResults(0);
        }


        // this.orcidStatus = this.errorCodes.NONE;

      },
      err => this.errorHandler(err, term)
    ));
  }

  private errorHandler(err: any, term: string) {
    if (err.status == 404) {
      this.getOrcidAuthors(term);
    } else {
      this.orcidStatus = this.errorCodes.ERROR;
      //console.log(err.status);
      ClaimResultSearchFormComponent.handleError("Error getting orcid author for term: " + term, err);
    }
  }

  private getOrcidAuthors(term: string) {
    this.orcidResultsNum = null;
    this.selectAuthorId = "0";
    this.orcidStatus = this.errorCodes.LOADING;
    //passing structures in order to fill them in service
    this.subscriptions.push(this._searchOrcidService.searchOrcidAuthors(StringUtils.URIEncode(term), this.properties).subscribe(
      data => {
        this.authorIds = data;
        if (data != null) {
          for (let i = 0; i < this.authorIds.length; i++) {
            this.getOrcidAuthor(this.authorIds[i], (i == 0));
          }
          if (this.authorIds.length == 0) {
            this.orcidStatus = this.errorCodes.NONE;
            this.orcidResultsNum = -1;
          }
        } else {
          this.orcidStatus = this.errorCodes.ERROR;
        }

      },
      err => {
        this.orcidStatus = this.errorCodes.ERROR;
        //console.log(err.status);
        ClaimResultSearchFormComponent.handleError("Error getting orcid authors for term: " + term + " and ids: " + JSON.stringify(this.authorIds), err);
      }
    ));
  }


  private getOrcidResultsById(id) {
    for (let i = 0; i < this.authors.length; i++) {
      if (this.authors[i].id == id) {
        this.getOrcidResults(i);
      }
    }
  }

  private getOrcidResults(index) {
    this.authorGivenName = this.authors[index].authorGivenName;
    this.authorFamilyName = this.authors[index].authorFamilyName;
    this.authorId = this.authors[index].id;
    this.orcidStatus = this.errorCodes.LOADING;
    this.subscriptions.push(this._searchOrcidService.searchOrcidPublications(this.authors[index].id, this.properties, true).subscribe(
      data => {
        if (data != null) {
          this.orcidResults = data;
          this.orcidResultsNum = data.length;
          this.orcidPage = 1;
          if ((this.orcidResultsNum % this.size) == 0) {
            this.totalPages = parseInt('' + (this.orcidResultsNum / this.size));
          } else {
            this.totalPages = parseInt('' + (this.orcidResultsNum / this.size + 1));
          }

          this.orcidResultsToShow = this.orcidResults.slice(0, 10);

          this.orcidStatus = this.errorCodes.DONE;
          if (this.orcidResultsNum == 0) {
            this.orcidStatus = this.errorCodes.NONE;
          }
          for (let i = 0; i < this.orcidResults.length; i++) {
            const entity: ClaimEntity = this.orcidResults[i];
            if (!entity.result.authors) {
              entity.result.authors = [];
            }
            entity.result.authors.push(this.authorFamilyName + ', ' + this.authorGivenName);
            if (entity.result.DOI != null) {
              this.enhanceInfoFromDOI(entity);
            }
          }
        } else {
          this.orcidResultsNum = 0;
          this.totalPages = 0;
          this.orcidStatus = this.errorCodes.NONE;
        }

      },
      err => {
        //console.log(err.status);
        ClaimResultSearchFormComponent.handleError("Error getting orcid publications for author id: " + this.authors[index].id, err);
        this.orcidStatus = this.errorCodes.ERROR;
      }
    ));


  }

  private enhanceInfoFromDOI(entity: ClaimEntity) {

    if (entity.result.DOI != null) {
      this.subscriptions.push(this._searchCrossrefService.searchCrossrefByDOIs([entity.result.DOI], this.properties, true).subscribe(
        data => {
          if (data != null && data[0] > 0 && data[1]) {
            let crossrefResult: ClaimEntity = data[1][0];
            if (entity.title == null || entity.title == "") {
              entity.title = crossrefResult.title;
            }
            if (crossrefResult.result.authors) {
              entity.result.authors = [];
              for (let i = 0; i < crossrefResult.result.authors.length; i++) {
                entity.result.authors.push(crossrefResult.result.authors[i]);
              }
            }
            if (entity.result.journal == null || entity.result.journal == "") {
              entity.result.journal = crossrefResult.result.journal;
            }
            if (entity.result.publisher == null || entity.result.publisher == "") {
              entity.result.publisher = crossrefResult.result.publisher;
            }
            if (entity.result.date == null || entity.result.date == "") {
              entity.result.date = crossrefResult.result.date;
            }

          } else {
          }
        },
        err => {
          ClaimResultSearchFormComponent.handleError("Error getting crossref by DOIs: " + entity['DOI'], err);
        }
      ));
    }
  }

  private crossrefPageChange($event) {
    this.crossrefPage = $event.value;
    this.crossrefResults = [];
    this.getCrossrefResults(this.keyword, this.size, this.crossrefPage);
  }

  private orcidPageChange($event) {
    this.orcidPage = $event.value;
    this.orcidResultsToShow = [];
    this.orcidResultsToShow = this.orcidResults.slice(($event.value - 1) * this.size, $event.value * this.size);
  }

  private openaireResultsPageChange($event) {
    this.openaireResultsPage = $event.value;
    this.openaireResults = [];
    this.searchOpenaire(this.keyword, this.size, this.openaireResultsPage, false);
  }

  datacitePageChange($event) {
    this.datacitePage = $event.value;
    this.dataciteResults = [];
    this.searchDatacite(this.keyword, 10, this.datacitePage);
    this.warningMessage = "";
    this.infoMessage = "";

  }


  private searchDatacite(term: string, size: number, page: number) {
    this.getDataciteResults(term, size, page);
    this.warningMessage = "";
    this.infoMessage = "";

  }




  createOpenaireQueryParams():string {
    let query = "";
/*    if (this.DOIs.length > 0) {
      let doisParams = "";
      for (let i = 0; i < this.DOIs.length; i++) {
        doisParams += (doisParams.length > 0 ? "&" : "") + 'doi="' + this.DOIs[i] + '"';
      }
      query += doisParams;
    } else if(this.keyword.length > 0){
      query += "q=" + StringUtils.quote(StringUtils.URIEncode(this.keyword));
    }*/
  if(this.keyword.length>0){
    query+=NewSearchPageComponent.createKeywordQuery("result",this.keyword,"q","=");
  }
    return query;
  }
  createOpenaireRefineQueryParams():string {
    let allFqs = "";
    if(this.openaireYear.length > 0 ){
      allFqs+='&fq=resultacceptanceyear exact \"'+this.openaireYear+'\"'
    }
    for (let filter of this.openaireResultsfilters){
      if(filter.countSelectedValues > 0){
        let count_selected=0;
        let fq = "";
        for (let value of filter.values){
          if(value.selected == true){
            count_selected++;
            fq+=(fq.length > 0 ? " " + filter.filterOperator + " ":"" ) + filter.filterId + " exact " + (StringUtils.quote(value.id));
          }
        }
        if(count_selected > 0){
          fq="&fq="+StringUtils.URIEncode(fq);
          allFqs += fq;
        }
      }
    }
    for (let i=0; i<this.rangeFilters.length; i++){
      let filter = this.rangeFilters[i];
      //selectedFromValue, selectedToValue, equalityOp, equalityOpFrom, equalityOpTo, filterOp ){
      allFqs+= NewSearchPageComponent.createRangeFilterQuery(this.rangeFields[i],filter.selectedFromValue, filter.selectedToValue, " within ", ">=" ,"<=", "and" )
    }

    if(this.resultTypes.publication && this.resultTypes.dataset && this.resultTypes.software && this.resultTypes.other){
      allFqs += "&type=results";
    }else{
        if(this.resultTypes.publication) {
          allFqs += "&type=publications";
        }
        if(this.resultTypes.dataset) {
          allFqs += "&type=datasets";
        }
        if(this.resultTypes.software) {
          allFqs += "&type=software";
        }
        if(this.resultTypes.other) {
          allFqs += "&type=other";
        }

    }
    return allFqs;

  }

  public static openaire2ClaimResults(data, properties): ClaimEntity[] {
    const claimResults = [];
    for (let i = 0; i < data.length; i++) {
      let item = data[i];
      let entity: ClaimEntity = new ClaimEntity();
      entity.result = new ClaimResult();
      entity.result.publisher = (item.publisher && item.publisher != "") ? item.publisher : null;
      entity.result.journal = null;
      entity.result.DOI = null;
      entity.id = item.id;
      entity.title = item.title.name;
      let prefixUrl = "";
      if(item.entityType == "publication"){
        prefixUrl = properties.searchLinkToPublication;
      }else if(item.entityType == "dataset"){
        prefixUrl = properties.searchLinkToDataset;
      }else if(item.entityType == "software"){
        prefixUrl = properties.searchLinkToSoftwareLanding;
      }else if(item.entityType == "other"){
        prefixUrl = properties.searchLinkToOrp;
      }
      entity.result.url = prefixUrl + entity.id;
      entity.result.source = String("openaire");
      entity.result.date = (item.year && item.year != "") ? item.year : null;
      entity.result.accessRights = (item.title && item.title.accessMode) ? String(item.title.accessMode) : "";

      entity.type = item.entityType;
      entity.result.embargoEndDate = (item.embargoEndDate && item.embargoEndDate != "") ? item.embargoEndDate : entity.result.embargoEndDate;
      if (item.publisher && item.publisher.length > 0) {
        entity.result.publisher = item.publisher;
      }
      entity.result.record = item;
      if (item.authors) {
        entity.result.authors = [];
        for (let author of item.authors) {
          entity.result.authors.push(author.fullName);
        }
      }
      claimResults.push(entity);
    }
    return claimResults;

  }

  private getDataciteResults(term: string, size: number, page: number) {
    this.dataciteStatus = this.errorCodes.LOADING;
    if (this.DOIs.length > 0) {
      let doiObservables: Array<Observable<any>> = new Array();
      for(let doi of this.DOIs){
        let ob = this._searchDataciteService.getDataciteResultByDOI(doi, this.properties, true);
        doiObservables.push(ob);

      }
      this.subscriptions.push(forkJoin(doiObservables).subscribe(
        data => {
          //if DOI not found or an error occured the result will be null -- remove null values
          for(let result of data){
            if(result){
              this.dataciteResults.push(result)
            }
          }
          this.datacitePage = page;
          this.dataciteResultsNum = this.dataciteResults.length;
          this.dataciteStatus = this.errorCodes.DONE;
          if (this.dataciteResultsNum == 0) {
            this.subscriptions.push(this._searchDataciteService.searchDataciteResults(StringUtils.URIEncode(term), size, page, this.properties, true).subscribe(
              data => {
                this.dataciteResults = data[1];
                this.datacitePage = page;
                this.dataciteResultsNum = data[0];
                this.dataciteStatus = this.errorCodes.DONE;
                if (this.dataciteResultsNum == 0) {
                  this.dataciteStatus = this.errorCodes.NONE;
                }

              },
              err => {

                this.dataciteStatus = this.errorCodes.ERROR;

                console.log(err);
                ClaimResultSearchFormComponent.handleError("Error getting datacite results for term: " + term, err);
              }));
          }
        }

        ));
    } else {


      this.subscriptions.push(this._searchDataciteService.searchDataciteResults(StringUtils.URIEncode(term), size, page, this.properties, true).subscribe(
        data => {
          this.dataciteResults = data[1];
          this.datacitePage = page;
          this.dataciteResultsNum = data[0];
          // console.log("Datacite " + this.dataciteResultsNum);
          this.dataciteStatus = this.errorCodes.DONE;
          if (this.dataciteResultsNum == 0) {
            this.dataciteStatus = this.errorCodes.NONE;
          }

        },
        err => {
          this.dataciteStatus = this.errorCodes.ERROR;
          //console.log(err);
          ClaimResultSearchFormComponent.handleError("Error getting datacite results for term: " + term, err);
        }
      ));
    }
  }

  public openaireTypeChanged() {
    // this.openaireResultsType = type;
    this.reloadOpenaire = true;
    this.openaireYear = "";
    this.openaireResultsfilters = [];
    this.search(false);

  }
  public yearChanged() {
    this.reloadOpenaire = true;
    this.search(false);

  }

  public clickTab(tab) {
    this.activeTab = tab;
    // this.search(false);
  }

  private static handleError(message: string, error) {
    console.error("Claim Result Search Form (component): " + message, error);
  }

  //OpenaireFilters:

  getSelectedValues(filter): any {
    var selected = [];
    if (filter.countSelectedValues > 0) {
      for (var i = 0; i < filter.values.length; i++) {
        if (filter.values[i].selected) {
          selected.push(filter.values[i]);
        }
      }
    }
    return selected;

  }

  private removeFilter(value: Value, filter: Filter) {
    filter.countSelectedValues--;
    if (value.selected == true) {
      value.selected = false;
    }
    // this.search(false);
    this.filterChanged(null);
  }

  public countFilters(): number {
    let filters = 0;
    for (let filter of this.openaireResultsfilters) {
      if (filter.countSelectedValues > 0) {
        filters += filter.countSelectedValues;
      }
    }
    for (let filter of this.rangeFilters) {
      if (filter.selectedFromValue || filter.selectedToValue) {
        filters += 1;
      }
    }
    return filters;
  }

  private clearFilters() {
    for (let i = 0; i < this.openaireResultsfilters.length; i++) {
      for (let j = 0; j < this.openaireResultsfilters[i].countSelectedValues; j++) {
        if (this.openaireResultsfilters[i].values[j].selected) {
          this.openaireResultsfilters[i].values[j].selected = false;
        }
        this.openaireResultsfilters[i].countSelectedValues = 0;
      }
    }
    for(let filter of this.rangeFilters){
      this.removeRangeFilter(filter);
    }
    this.filterChanged(null);
  }
  dateFilterChanged(filter:RangeFilter) {
    if (filter.selectedFromValue && filter.selectedToValue) {
      filter.selectedFromAndToValues = filter.selectedFromValue + "-" + filter.selectedToValue;
    } else if (filter.selectedFromValue) {
      filter.selectedFromAndToValues = "From " + filter.selectedFromValue;
    } else if (filter.selectedToValue) {
      filter.selectedFromAndToValues = "Until " + filter.selectedToValue;
    }
    this.filterChanged(null);
  }
  filterChanged($event) {
    // console.log("filterChanged");
    this.reloadOpenaire = true;
    this.search(false);

  }
  public checkSelectedFilters(filters:Filter[], prevFilters:Filter[]){
    for(let i=0; i< filters.length ; i++){
      let filter:Filter = filters[i];
      filter.countSelectedValues = 0;
      let prevFilterSelectedValues:string[] = [];
      for(let j=0; j< prevFilters.length ; j++){
        if(filters[i].filterId == prevFilters[j].filterId){
          if(prevFilters[j].countSelectedValues >0){
            for(let filterValue of prevFilters[j].values) {
              if(filterValue.selected){
                prevFilterSelectedValues.push(filterValue.id);
              }
            }

          }
          break;
        }
      }
      for(let filterValue of filter.values) {
        if(prevFilterSelectedValues.indexOf(filterValue.id) > -1) {
          filterValue.selected = true;
          filter.countSelectedValues++;
        }

      }
      filter.countAllValues = filter.values.length;
    }
    return filters;
  }
  countTotalPages(totalResults: number): number {
    let totalPages:any = totalResults/(this.size);
    if(!(Number.isInteger(totalPages))) {
      totalPages = (parseInt(totalPages, 10) + 1);
    }
    return totalPages;
  }
/*  getTotalOpenaireNumber():number{
    let count = 0;
    for(let i=0; i<this.openaireResultsType.length; i++){
      if(this.openaireResultsType[i]["count]"]!=null){
        count+= this.openaireResultsType[i]["count]"];
      }
    }
    return count;
  }*/
/*  public _formatName(value, number){
    let maxLineLength = 29;
    //1 space after checkbox
    //3 space before number + parenthesis
    if(number && value.length+number.toLocaleString().length +1 +3> maxLineLength){
      return value.substr(0, (maxLineLength- 3 -4 - number.toLocaleString().length))+'...';
    }else if(!number && value.length + 1 > maxLineLength){
      return value.substr(0, (maxLineLength- 3 -1 ))+'...';
    }
    return value;
  }*/

  public removeRangeFilter(filter: RangeFilter) {
    filter.selectedFromValue = null;
    filter.selectedToValue = null;
    filter.selectedFromAndToValues = null;
    this.filterChanged(null);
  }

}
