Project

General

Profile

1
import {Component, ElementRef, Input, Output, ViewChild} from '@angular/core';
2
import {Location} from '@angular/common';
3
import {ActivatedRoute, Router} from '@angular/router';
4
import {Meta, Title} from '@angular/platform-browser';
5

    
6
import {AdvancedField, Filter, Value} from './searchHelperClasses.class';
7
import {SearchCustomFilter, SearchUtilsClass} from './searchUtils.class';
8
import {ModalLoading} from '../../utils/modal/loading.component';
9
import {Dates, Identifier, StringUtils} from '../../utils/string-utils.class';
10
import {ErrorCodes} from '../../utils/properties/errorCodes';
11
import {RouterHelper} from '../../utils/routerHelper.class';
12

    
13
import {PiwikService} from '../../utils/piwik/piwik.service';
14
import {EnvProperties} from '../../utils/properties/env-properties';
15
import {SEOService} from '../../sharedComponents/SEO/SEO.service';
16
import {HelperService} from "../../utils/helper/helper.service";
17
import {SearchFields} from "../../utils/properties/searchFields";
18
import {RefineResultsUtils} from "../../services/servicesUtils/refineResults.class";
19
import {RangeFilter} from "../../utils/rangeFilter/rangeFilterHelperClasses.class";
20
import {ZenodoInformationClass} from "../../deposit/utils/zenodoInformation.class";
21
import {Breadcrumb} from "../../utils/breadcrumbs/breadcrumbs.component";
22

    
23
declare var UIkit: any;
24

    
25
@Component({
26
  selector: 'new-search-page',
27
  templateUrl: 'newSearchPage.component.html'
28
})
29
export class NewSearchPageComponent {
30
  @ViewChild('offcanvas_element') offcanvasElement: ElementRef;
31

    
32
  @Input() piwikSiteId = null;
33
  @Input() hasPrefix: boolean = true;
34
  @Input() pageTitle = "";
35
  @Input() results = [];
36
  @Input() type;
37
  @Input() entityType;
38
  @Input() searchUtils: SearchUtilsClass = new SearchUtilsClass();
39
  @Input() fieldIds: string[];
40
  @Input() fieldIdsMap;//:{ [key:string]:{ name:string, operator:string, type:string, indexField:string, equalityOperator:string  }} ;
41
  @Input() selectedFields: AdvancedField[];
42
  @ViewChild(ModalLoading) loading: ModalLoading;
43
  @Input() csvParams: string;
44
  @Input() csvPath: string;
45
  @Input() simpleSearchLink: string = "";
46
  @Input() advancedSearchLink: string = "";
47
  @Input() disableForms: boolean = false;
48
  @Input() loadPaging: boolean = true;
49
  @Input() oldTotalResults: number = 0;
50
  @Input() openaireLink: string;
51
  @Input() customFilter: SearchCustomFilter;
52
  @Input() sort: boolean = false;
53
  @Input() searchFormClass: string = "searchForm";
54
  //From simple:
55
  @Input() rangeFilters: RangeFilter[] = [];
56
  @Input() rangeFields: string[][] = [];
57
  @Input() refineFields = [];
58
  @Input() filters = [];
59
  selectedFilters: number = 0;
60
  selectedRangeFilters: number = 0;
61
  private searchFieldsHelper: SearchFields = new SearchFields();
62
  @Input() newQueryButton: boolean = true;
63
  public showUnknownFilters: boolean = false; // when a filter exists in query but has no results, so no filters returned from the query
64
  URLCreatedFilters: Filter[] = [];
65
  URLCreatedRangeFilters: RangeFilter[] = [];
66
  @Input() showRefine: boolean = true;
67
  @Input() tableViewLink: string;
68
  @Input() usedBy: string = "search";
69
  @Input() public zenodoInformation: ZenodoInformationClass = new ZenodoInformationClass();
70
  @Input() showLastIndex: boolean = true;
71
  @Input() showResultCount: boolean = true;
72
  @Input() showMoreFilterValuesInline: boolean = true;
73
  @Input() filterValuesNum: number = 6;
74
  @Input() keywordFields = [];
75
  @Input() simpleView: boolean = true;
76
  @Input() formPlaceholderText = "Type Keywords...";
77
  @Input() resultTypes = null;
78
  @Input() quickFilter: { filter: Filter, selected: boolean, filterId: string, value: string };
79
  @Input() includeOnlyResultsAndFilter:boolean = false;
80
  @Input() showBreadcrumb:boolean = false;
81
  @Input() lastIndex: boolean = true;
82

    
83
  piwiksub: any;
84
  public parameterNames: string[] = [];
85
  public parameterValues: string[] = [];
86

    
87
  public csvLimit: number = 0;
88
  public pagingLimit: number = 0;
89
  public resultsPerPage: number = 0;
90
  isPiwikEnabled = false;
91
  properties: EnvProperties;
92
  public pageContents = null;
93
  public divContents = null;
94
  public routerHelper: RouterHelper = new RouterHelper();
95
  public errorCodes: ErrorCodes = new ErrorCodes();
96
  breadcrumbs:Breadcrumb[] = [];
97
  url = null;
98

    
99
  @Input() entitiesSelection:boolean = true;
100
  @Input() showAdvancedSearchLink:boolean = true;
101
  constructor(private route: ActivatedRoute,
102
              private location: Location,
103
              private _meta: Meta,
104
              private _title: Title,
105
              private _piwikService: PiwikService,
106
              private router: Router,
107
              private seoService: SEOService,
108
              private helper: HelperService) {
109
  }
110

    
111
  ngOnInit() {
112
    this.route.data
113
      .subscribe((data: { envSpecific: EnvProperties }) => {
114
        this.properties = data.envSpecific;
115
        //this.getDivContents();
116
        this.getPageContents();
117
        this.pagingLimit = data.envSpecific.pagingLimit;
118
        this.resultsPerPage = data.envSpecific.resultsPerPage;
119
        this.csvLimit = data.envSpecific.csvLimit;
120
        this.isPiwikEnabled = data.envSpecific.enablePiwikTrack;
121
        if (typeof window !== 'undefined') {
122
          this.updateUrl(data.envSpecific.baseLink + location.pathname);
123
          this.url = data.envSpecific.baseLink + location.pathname
124
        }
125
        if (typeof document !== 'undefined' && this.isPiwikEnabled) {
126
          this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe();
127
        }
128
      });
129

    
130
    var description = "Openaire, search, repositories, open access, type, content provider, funder, project, " + this.pageTitle;
131

    
132
    this.updateTitle(this.pageTitle);
133
    this.updateDescription(description);
134

    
135
    this.searchUtils.baseUrl = "/" + this.searchUtils.baseUrl;
136
    this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.router.url, false);
137
    this.breadcrumbs.push({name: 'home', route: '/'});
138
    if(this.simpleView) {
139
      this.breadcrumbs.push( {name: "Search", route: this.simpleSearchLink});
140
    }else if(!this.simpleView && this.advancedSearchLink) {
141
      this.breadcrumbs.push({name: "Advanced Search", route: this.advancedSearchLink});
142
    }
143

    
144

    
145
  }
146

    
147
  private getPageContents() {
148
    this.helper.getPageHelpContents(this.properties, (this.customFilter) ? this.customFilter.valueId : null, this.router.url).subscribe(contents => {
149

    
150
      this.pageContents = contents;
151
    })
152
  }
153

    
154
  private getDivContents() {
155
    this.helper.getDivHelpContents(this.properties, (this.customFilter) ? this.customFilter.valueId : null, this.router.url).subscribe(contents => {
156
      this.divContents = contents;
157
    })
158
  }
159

    
160
  ngOnDestroy() {
161
    if (this.piwiksub) {
162
      this.piwiksub.unsubscribe();
163
    }
164
  }
165

    
166
  updateDescription(description: string) {
167
    this._meta.updateTag({content: description}, "name='description'");
168
    this._meta.updateTag({content: description}, "property='og:description'");
169
  }
170

    
171
  updateTitle(title: string) {
172
    var _prefix = "";
173
    if (this.hasPrefix) {
174
      _prefix = "OpenAIRE | ";
175
    }
176
    var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title);
177
    this._title.setTitle(_title);
178
    this._meta.updateTag({content: _title}, "property='og:title'");
179
  }
180

    
181
  updateUrl(url: string) {
182
    this._meta.updateTag({content: url}, "property='og:url'");
183
  }
184

    
185

    
186
  clearFilters() {
187
    for (var i = 0; i < this.filters.length; i++) {
188
      for (var j = 0; j < this.filters[i].countSelectedValues; j++) {
189
        if (this.filters[i].values[j].selected) {
190
          this.filters[i].values[j].selected = false;
191
        }
192
        this.filters[i].countSelectedValues = 0;
193
      }
194
    }
195
    this.selectedFilters = 0;
196
    for(let i = 0; i < this.rangeFilters.length; i++) {
197
      this.rangeFilters[i].selectedFromValue = null;
198
      this.rangeFilters[i].selectedToValue = null;
199
    }
200
    this.selectedRangeFilters = 0;
201
    if (this.quickFilter) {
202
      this.removeValueFromQuickFilter();
203
    }
204
    this.goTo(1);
205
    // this.clearKeywords();
206
  }
207

    
208
  goTo(page: number = 1) {
209
    if(this.offcanvasElement) {
210
      UIkit.offcanvas(this.offcanvasElement.nativeElement).hide();
211
    }
212

    
213
    this.searchUtils.page = page;
214
    this.buildPageURLParameters(this.filters, this.rangeFilters, true);
215
    this.router.navigate([this.searchUtils.baseUrl], {queryParams: this.routerHelper.createQueryParams(this.parameterNames, this.parameterValues)});
216
    /* Code For Piwik*/
217
    if (typeof localStorage !== 'undefined') {
218
      //console.log("In PreviousRouteRecorder : "+this.router.url );
219
      localStorage.setItem('previousRoute', this.router.url);
220
    }
221
    if (this.isPiwikEnabled && (typeof document !== 'undefined')) {
222
      this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe();
223
    }
224
    /* End Piwik Code */
225
  }
226

    
227
  queryChanged() {
228

    
229
    this.goTo(1);
230
  }
231

    
232

    
233
  sizeChanged($event) {
234
    this.searchUtils.size = $event.value;
235
    this.goTo(1);
236
  }
237

    
238
  sortByChanged($event) {
239
    this.searchUtils.sortBy = $event.value;
240
    this.goTo(1);
241
  }
242

    
243

    
244
  getOperatorParameter(parameter: string): string {
245
    for (let id of this.fieldIds) {
246
      if (this.fieldIdsMap[id]["param"] == parameter) {
247
        return this.fieldIdsMap[id]["operator"];
248
      }
249
    }
250
  }
251

    
252
  /*
253
* Get A sub-array of this.refineFields array, which contains the ids of the selected filters
254
*/
255
  public getSelectedFilters(): string[] {
256
    var selected: string[] = [];
257
    for (var i = 0; i < this.filters.length; i++) {
258
      var filter: Filter = this.filters[i];
259
      if (filter.countSelectedValues > 0) {
260
        selected.push(filter.filterId);
261
      }
262
    }
263
    return selected;
264
  }
265

    
266
  /*
267
    * Get A sub-array of this.refineFields array, which contains the ids of the selected parameters
268
    */
269
  private getSelectedParameters(): string[] {
270
    var selected: string[] = [];
271
    for (var i = 0; i < this.refineFields.length; i++) {
272
      if (this.parameterNames.indexOf(this.refineFields[i]) != -1) {
273
        selected.push(this.refineFields[i]);
274
      }
275
    }
276
    return selected;
277
  }
278

    
279
  /*
280
  * Get A sub-array of this.refineFields array, which hides hidden fields (e.g Funding level 0,1,2,..), and contains those that depend on another fields (e.g  Funding level 0 if Funder is selected )
281
  */
282
  public getFields(): string[] {
283
    var selected_filters: string[] = this.getSelectedFilters();
284
    if (selected_filters.length == 0) {
285
      selected_filters = this.getSelectedParameters();
286
    }
287
    var fields: string[] = [];
288
    for (var i = 0; i < this.refineFields.length; i++) {
289
      var dependentTo = this.searchFieldsHelper.DEPENDENT_FIELDS[this.refineFields[i]];
290

    
291
      //if filter is not marked as hidden OR it is hidden but it is dependent to a field that it IS selected
292
      if (this.searchFieldsHelper.HIDDEN_FIELDS.indexOf(this.refineFields[i]) == -1 || (selected_filters.indexOf(dependentTo) != -1) || (selected_filters.indexOf(this.refineFields[i]) != -1)) {
293
        fields.push(this.refineFields[i]);
294
      }
295
    }
296
    return fields;
297
  }
298

    
299
  /*
300
  * Get a query  string of all fields, that want to get from search (e.g. &fields=funderid&fields=projectstartyear&...))
301
  */
302
  public getRefineFieldsQuery(): string {
303

    
304
    var fields: string[] = this.getFields();
305
    var fieldsStr = ""
306
    for (var i = 0; i < fields.length; i++) {
307
      fieldsStr += "&fields=" + fields[i];
308
    }
309
    return "&refine=true" + fieldsStr;
310
  }
311

    
312

    
313
  /*
314
  * Mark as check the new filters that are selected, when you get them from search
315
  */
316
  public checkSelectedFilters(filters: Filter[]) {
317
    this.filters = filters;
318
    for (var i = 0; i < filters.length; i++) {
319
      var filter: Filter = filters[i];
320
      filter.countSelectedValues = 0;
321
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
322
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
323
        for (let filterValue of filter.values) {
324
          if (values.indexOf(StringUtils.quote(filterValue.id)) > -1) {
325
            filterValue.selected = true;
326
            filter.countSelectedValues++;
327
          } else {
328
            filterValue.selected = false;
329

    
330
          }
331
        }
332
      } else if (this.quickFilter && this.quickFilter.filterId == filter.filterId && this.quickFilter.selected) {
333
        for (let filterValue of filter.values) {
334
          if (filterValue.id == this.quickFilter.value) {
335
            filterValue.selected = true;
336
            filter.countSelectedValues++;
337
          } else {
338
            filterValue.selected = false;
339
          }
340
        }
341
      } else {
342
        for (let filterValue of filter.values) {
343
          filterValue.selected = false;
344
        }
345
      }
346
      if (this.quickFilter && filter.filterId == this.quickFilter.filterId) {
347
        this.quickFilter.filter = filter;
348
      }
349
    }
350
    this.filterFilterValues(this.filters);
351
    return filters;
352
  }
353

    
354
  /*
355
* Mark as check the new range filters that are selected
356
*/
357
  public checkSelectedRangeFilters(filters: RangeFilter[]) {
358
    //console.log("checkSelectedRangeFilters: parameterNames.length: "+this.parameterNames.length);
359

    
360
    this.rangeFilters = filters;
361
    for (let i = 0; i < filters.length; i++) {
362
      let filter: RangeFilter = filters[i];
363

    
364
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
365
        //console.log(filter.filterId + " "+this.parameterNames.indexOf(filter.filterId) );
366
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
367
        let operators: string [] = (StringUtils.URIDecode(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
368
        if (values.length == operators.length) {
369
          for (let j = 0; j < values.length; j++) {
370
            if (this.fieldIdsMap[filter.originalFilterIdFrom+"-range-"+filter.originalFilterIdTo].filterType == "range") {
371
              let value: string = StringUtils.unquote(values[j]);
372
              let validDates: boolean = true;
373

    
374
              let years: string[] = (value.substring(5)).split(":");
375
              let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
376
              let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
377
              //console.log("checkSelectedRangeFilters: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
378
              if(yearFrom) {
379
                filter.selectedFromValue = yearFrom;
380
              }
381
              if(yearTo) {
382
                filter.selectedToValue = yearTo;
383
              }
384
              if(yearFrom && yearTo) {
385
                filter.selectedFromAndToValues = yearFrom + "-" + yearTo;
386
              } else if(yearFrom) {
387
                filter.selectedFromAndToValues = "From " + yearFrom;
388
              } else if(yearTo) {
389
                filter.selectedFromAndToValues = "Until " + yearTo;
390
              }
391

    
392
              if(!yearFrom && !yearTo) {
393
                validDates = false;
394
              }
395

    
396
              // if (value.length < 14) {
397
              //   validDates = false;
398
              //   console.log("not valid (length<14)");
399
              // } else {
400
              //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
401
              //     validDates = false;
402
              //     console.log("not valid years");
403
              //   } else {
404
              //     filter.selectedFromValue = value.substring(5, 9);
405
              //     filter.selectedToValue = value.substring(10, 14);
406
              //     console.log(filter);
407
              //   }
408
              // }
409
            }
410
          }
411
        }
412
      } else {
413
        filter.selectedFromValue = null;
414
        filter.selectedToValue = null;
415
      }
416
    }
417
    return this.rangeFilters;
418
  }
419

    
420
  /*
421
  * For Funder filters - if funder selected
422
  */
423
  public filterFilterValues(filters: Filter[]) {
424
    var funders = [];
425
    var funder_prefix = [];
426
    for (var i = 0; i < filters.length; i++) {
427

    
428
      var filter: Filter = filters[i];
429
      //  console.log(filter.filterId);
430
      if (filter.filterId.indexOf("funder") != -1 && this.parameterNames.indexOf(filter.filterId) != -1) {
431
        let funders = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
432
        for (let funder of funders) {
433
          funder_prefix.push(StringUtils.unquote(funder).split("____")[0]);
434
        }
435
        //  console.log(funder_prefix );
436
      } else if (filter.filterId.indexOf("funding") != -1) {
437
        //  console.log(" funding: "+filter.filterId );
438
        var filteredValues = []
439
        for (let filterValue of filter.values) {
440
          var value_prefix = filterValue.id.split("____")[0];
441
          //  console.log("Value prefix: "+value_prefix );
442
          if (funder_prefix.indexOf(value_prefix) != -1) {
443
            //  console.log("here" + value_prefix);
444
            filteredValues.push(filterValue);
445
          }
446

    
447
        }
448
        if (filteredValues.length > 0) {
449
          filter.values = filteredValues;
450
        }
451
      }
452

    
453
    }
454

    
455
    return filters;
456
  }
457

    
458
  public countSelectedFilters(filters: Filter[]): number {
459
    this.selectedFilters = 0;
460
    for (let filter of filters) {
461
      if (filter.countSelectedValues > 0) {
462
        this.selectedFilters += filter.countSelectedValues;
463
      }
464
    }
465
    return this.selectedFilters;
466
  }
467

    
468
  public countSelectedRangeFilters(rangeFilters: RangeFilter[]) : number {
469
    this.selectedRangeFilters = 0;
470
    for(let filter of rangeFilters) {
471
      if(filter.selectedFromValue || filter.selectedToValue) {
472
        this.selectedRangeFilters++;
473
      }
474
    }
475
    return this.selectedRangeFilters;
476
  }
477

    
478
  private clearKeywords() {
479
    if (this.searchUtils.keyword.length > 0) {
480
      this.searchUtils.keyword = '';
481
    }
482
    this.goTo(1);
483
  }
484

    
485
  public removeFilter(value: Value, filter: Filter) {
486
    filter.countSelectedValues--;
487
    this.selectedFilters--;
488
    if (value.selected == true) {
489
      value.selected = false;
490
    }
491
    if (this.quickFilter && this.quickFilter.filterId == filter.filterId) {
492
      this.removeValueFromQuickFilter();
493
    }
494
    this.goTo(1);
495
  }
496

    
497
  public removeRangeFilter(filter: RangeFilter) {
498
    filter.selectedFromValue = null;
499
    filter.selectedToValue = null;
500
    this.goTo(1);
501
  }
502

    
503
  getSelectedValues(filter): any {
504
    var selected = [];
505
    if (filter.countSelectedValues > 0) {
506
      for (var i = 0; i < filter.values.length; i++) {
507
        if (filter.values[i].selected) {
508
          selected.push(filter.values[i]);
509
        }
510
      }
511
    }
512
    return selected;
513

    
514
  }
515

    
516
  filterChanged($event) {
517
    if (this.quickFilter && this.quickFilter.filter) {
518
      this.removeValueFromQuickFilter();
519
    }
520
    this.goTo(1);
521

    
522
  }
523

    
524
  /**
525
   * if there is a change in the values of the quick filter, this function has to be run, to also update the quickFilter
526
   */
527
  removeValueFromQuickFilter() {
528
    if (this.quickFilter.filter.countSelectedValues == 0) {
529
      this.quickFilter.selected = false;
530
    } else {
531
      let isQuickEnabled = false;
532
      for (let filterValue of this.quickFilter.filter.values) {
533
        isQuickEnabled = (filterValue.name == this.quickFilter.value)
534
      }
535
      this.quickFilter.selected = (isQuickEnabled && this.quickFilter.filter.countSelectedValues == 1);
536
    }
537
  }
538

    
539
  // for loading
540
  public openLoading() {
541
    this.loading.open();
542
  }
543

    
544
  public closeLoading() {
545
    this.loading.close();
546
  }
547

    
548
  /**
549
   * Build advanced search Filters based on the URL parameters
550
   * @param params
551
   */
552
  createAdvancedSearchSelectedFiltersFromNewURLParameters(params) {
553
    for (let i = 0; i < Object.keys(params).length; i++) {
554
      if(params["f"+i] && params["fv"+i]   ) {
555
        let fieldId = params["f" + i].split(",")[0];
556
        let operator = (params["f" + i].split(",").length  >1 )?params["f" + i].split(",")[1]:"and";
557
        let fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
558

    
559
        if (!this.fieldIdsMap[fieldId]) {
560
          console.error("Field: " + fieldId + " not found in fieldIds map");
561
          continue;
562
        }
563
        let value: string = StringUtils.URIDecode(params["fv"+i]);
564
        if (this.fieldIdsMap[fieldId].type == "date") {
565
            let validDates: boolean = true;
566
            let dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operator);
567
            if (value.indexOf("range") != -1) {
568
              dateField.dateValue.type = "range";
569
              if (value.length < 26) {
570
                validDates = false;
571
              } else {
572
                if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
573
                  validDates = false;
574
                } else {
575
                  dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
576
                  dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
577
                }
578
              }
579
              //  "rangeYYYY-MM-DD:YYYY-MM-DD"
580
            } else {
581
              dateField.dateValue.setDatesByType(value);
582
            }
583
            if (validDates) {
584
              this.selectedFields.push(dateField);
585
            }
586

    
587
          } else {
588
            this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type,value, operator));
589
          }
590

    
591
        }
592
      }
593
  }
594
  /**
595
   * Build advanced search Filters based on the URL parameters
596
   * @param params
597
   */
598
  createAdvancedSearchSelectedFiltersFromURLParameters(params) {
599
    this.createAdvancedSearchSelectedFiltersFromNewURLParameters(params);
600
    for (var i = 0; i < this.fieldIds.length; i++) {
601
      var fieldId = this.fieldIds[i];
602
      var fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
603
      if (!this.fieldIdsMap[fieldId]) {
604
        console.error("Field: " + fieldId + " not found in fieldIds map");
605
        continue;
606
      }
607

    
608
      var operatorId = this.getOperatorParameter(fieldparam);
609
      if (params[fieldparam] != undefined && params[operatorId] != undefined) {
610
        var values: string [] = StringUtils.URIDecode(params[fieldparam]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
611
        var operators: string [] = (StringUtils.URIDecode(params[operatorId])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
612
        if (values.length == operators.length) {
613
          for (var j = 0; j < values.length; j++) {
614
            if (this.fieldIdsMap[fieldId].type == "date") {
615
              var value: string = StringUtils.unquote(values[j]);
616
              var validDates: boolean = true;
617
              var dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operators[j]);
618
              if (value.indexOf("range") != -1) {
619
                dateField.dateValue.type = "range";
620
                if (value.length < 26) {
621
                  validDates = false;
622
                } else {
623
                  if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
624
                    validDates = false;
625
                  } else {
626
                    dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
627
                    dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
628
                  }
629
                }
630
                //  "rangeYYYY-MM-DD:YYYY-MM-DD"
631
              } else {
632
                dateField.dateValue.setDatesByType(value);
633
              }
634
              if (validDates) {
635
                this.selectedFields.push(dateField);
636
              }
637

    
638
            } else {
639
              this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, values[j], operators[j]));
640
            }
641
          }
642
        }
643
      }
644
    }
645
    if (params['keyword'] && params['keyword'].length > 0) {
646
      this.selectedFields.push(new AdvancedField(this.fieldIds[0], this.fieldIdsMap[this.fieldIds[0]].param, this.fieldIdsMap[this.fieldIds[0]].name, this.fieldIdsMap[this.fieldIds[0]].type, params['keyword'], "and"));
647
    }
648
    if (this.selectedFields.length == 0) {
649
      this.selectedFields.push(new AdvancedField(this.fieldIds[0], this.fieldIdsMap[this.fieldIds[0]].param, this.fieldIdsMap[this.fieldIds[0]].name, this.fieldIdsMap[this.fieldIds[0]].type, "", "and"));
650
    }
651
  }
652

    
653
  /**
654
   * Create Search API query based on the selected fields of the advanced form
655
   */
656
  getSearchAPIQueryForAdvancedSearhFields() {
657

    
658
    var params = "";
659
    var countParams = 0;
660
    for (var i = 0; i < this.selectedFields.length; i++) {
661
      if (this.fieldIdsMap[this.selectedFields[i].id] != undefined && (this.selectedFields[i].value != "" || this.selectedFields[i].type == "date")) {
662
        //console.log("createQueryParameters::"+this.selectedFields[i].type);
663
        if (this.selectedFields[i].type == "date") {
664
          if (this.selectedFields[i].dateValue.type != "any") {
665
            params += (countParams == 0 ? "" : this.selectedFields[i].operatorId) + " " + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + StringUtils.URIEncode(Dates.getDateToString(this.selectedFields[i].dateValue.from)) + " "
666
              + StringUtils.URIEncode(Dates.getDateToString(this.selectedFields[i].dateValue.to)) + '"' + " ";
667
          }
668
        } else {
669
          if (this.selectedFields[i].id == "q") {
670
            // console.log(this.selectedFields[i].value)
671
/*            var op = "";
672
            var doisParams = "";
673
            if ((this.entityType == 'publication' || this.entityType == 'dataset' || this.entityType == 'software' || this.entityType == 'other' || this.entityType == "result")) {
674
              var DOIs: Identifier[] = Identifier.getIdentifiersFromString(this.selectedFields[i].value);
675
              for (let identifier of DOIs) {
676
                // console.log(identifier)
677
                // pidclassid exact \"doi\" and pid exact \"10.1016/j.nima.2015.11.134\"
678
                //and (authorid exact \"0000-0001-7291-3210 \" )"
679
                if(identifier.class == "ORCID"){
680
                  doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + identifier.id + '")';
681
                }else{
682
                  doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  identifier.id + '")';
683
                }
684
              }
685
            }
686
            if (doisParams.length > 0) {
687
              params += this.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId ,countParams,true, true) + " or " + doisParams;
688
            } else {
689
              params += this.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId,countParams,true);
690
            }*/
691
            params +=(countParams == 0 ? "" : " " + this.selectedFields[i].operatorId + " ") + NewSearchPageComponent.createKeywordQuery(this.entityType,this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams);
692
            //TODO deposit case
693
            // console.log(this.usedBy)
694
            // console.log(this.keywordFields)
695

    
696
            if(this.usedBy == "deposit") {
697

    
698
              if(this.keywordFields.length > 0) {
699
                params += " or ("
700
              }
701
              for(let j=0; j< this.keywordFields.length ; j++) {
702
                if(j > 0) {
703
                  params += " or "
704
                }
705
                params += NewSearchPageComponent.createQuotedKeywordQuery(this.selectedFields[i].value, this.keywordFields[j].name, " or ", countParams,false);
706
                // let field = this.keywordFields[i];
707
                //keywordQuery += field.name+field.equalityOperator+StringUtils.URIEncode(keyword);
708
                // params += field.name+field.equalityOperator+StringUtils.quote(StringUtils.URIEncode(keyword));
709
              }
710
              if(this.keywordFields.length > 0) {
711
                params += " ) "
712
              }
713
            }
714

    
715
          } else if (countParams == 0 && this.selectedFields[i].operatorId == "not" && this.fieldIdsMap[this.selectedFields[i].id].equalityOperator != "=") {
716
            params += " " + this.selectedFields[i].id + " <> " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
717
          } else if(this.fieldIdsMap[this.selectedFields[i].id].equalityOperator == "=") {
718
            params+=NewSearchPageComponent.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams, false);
719
          }else{
720
              params += (countParams == 0 ? "" : " " + this.selectedFields[i].operatorId + " ") + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + encodeURIComponent(this.selectedFields[i].value) + '"' + " ";
721

    
722
          }
723
        }
724
        countParams++;
725
      }
726
    }
727

    
728
    if (this.customFilter) {
729
      params += (countParams == 0 ? "" : " and ") + this.customFilter.queryFieldName + " exact " + StringUtils.quote((this.customFilter.valueId));
730
    }
731
    // console.log("ParameterS:")
732
    // console.log(params)
733
    return params;
734
  }
735
  public static createKeywordQuery(entityType:string, value:string, id, operatorId, countParams=0){
736
    let params = "";
737
    let doisParams = "";
738
    if ((entityType == 'publication' || entityType == 'dataset' || entityType == 'software' || entityType == 'other' || entityType == "result")) {
739
      var DOIs: Identifier[] = Identifier.getIdentifiersFromString(value);
740
      for (let identifier of DOIs) {
741
        // console.log(identifier)
742
        // pidclassid exact \"doi\" and pid exact \"10.1016/j.nima.2015.11.134\"
743
        //and (authorid exact \"0000-0001-7291-3210 \" )"
744
        if(identifier.class == "ORCID"){
745
          doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + identifier.id + '")';
746
        }else{
747
          doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  identifier.id + '")';
748
        }
749
      }
750
    }
751
    if (doisParams.length > 0) {
752
      params += "(" + this.createQuotedKeywordQuery(value, id, operatorId ,countParams,true, true) + " or " + doisParams+")";
753
    } else {
754
      params += this.createQuotedKeywordQuery(value, id, operatorId,countParams,true);
755
    }
756
    return params;
757

    
758
  }
759
  private static createQuotedKeywordQuery(fieldValue, fieldId, fieldOperator, countParams:number, isSearchAll:boolean, forceQuotted:boolean=false){
760
    let params = "";
761
    let quotedParts = (fieldValue)?fieldValue.match(/(["'])(.*?)*?\1/g):[];
762
    // params+= (countParams == 0 ? "" : fieldOperator) +
763
    params+=   " (";
764
    if(forceQuotted){
765
      return this.getQuotedQueryPart(fieldId, '"'+ fieldValue+'"',isSearchAll);
766
    }
767
    if(quotedParts && quotedParts.length == 1 && quotedParts[0] == fieldValue ){
768
      params+=this.getQuotedQueryPart(fieldId, fieldValue,isSearchAll);
769
    }else if( quotedParts && quotedParts.length > 0){
770
      for(let i=0; i< quotedParts.length; i++){
771
        params+=(i>0)?" and ":"";
772
        params+=this.getQuotedQueryPart(fieldId, quotedParts[i],isSearchAll);
773
      }
774
      let startPoint = 0;
775
      let endPoint = 0;
776
      for(let i=0; i< quotedParts.length; i++){
777
        let index = fieldValue.indexOf(quotedParts[i]);
778
        endPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+1]):fieldValue.length;
779
        // console.log(fieldValue.indexOf(quotedParts[i+1]) +" - "+fieldValue.length);
780
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
781
        if(index==startPoint){
782
          startPoint +=quotedParts[i].length;
783
        }else if(startPoint < index){
784
          endPoint = index;
785
        }
786
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
787
        if(decodeURIComponent(fieldValue.substring(startPoint,endPoint)).split(" ").join("").length > 0) {
788
          params += " and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint, endPoint), isSearchAll);
789
        }
790
        // console.log("For "+i+"  " +params+" SP "+ startPoint+" EP: "+endPoint);
791
        // startPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+i]):fieldValue.length;//(startPoint<index  )?(index + quotedParts[i].length):fieldValue.length;
792
        startPoint = ((i+1<quotedParts.length)?(fieldValue.indexOf(quotedParts[i+1])+quotedParts[i+1].length):(endPoint== index?(index+quotedParts[i].length):endPoint));
793
      }
794
      if(startPoint !=fieldValue.length && decodeURIComponent(fieldValue.substring(startPoint,fieldValue.length)).split(" ").join("").length > 0){
795
        params+=" and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint,fieldValue.length),isSearchAll);
796
      }
797
    }else{
798
      params+=this.getNoQuotedQueryPart(fieldId, fieldValue,isSearchAll);
799
    }
800
    params += ")";
801
    return params;
802
  }
803

    
804
  private static getQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
805
      return (isSearchAll?"__all":fieldId)+" exact "+StringUtils.URIEncode(value);
806
  }
807
  private static getNoQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
808
    if(isSearchAll){
809
      return StringUtils.URIEncode(value);
810
    }else{
811
      return fieldId+"="+ StringUtils.URIEncode(value);
812
    }
813
  }
814

    
815
  /**
816
   * Create Search API query based on the filters of refine fields
817
   * @param URLparams
818
   * @param firstLoad
819
   */
820
  getSearchAPIQueryForRefineFields(URLparams, firstLoad: boolean) {
821

    
822
    var allFqs = "";
823
    // console.log(this.refineFields)
824
    for (var i = 0; i < this.refineFields.length; i++) {
825
      var filterId = this.refineFields[i];
826

    
827
      if (URLparams[filterId] != undefined) {
828
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterId]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
829
        var countvalues = 0;
830
        var fq = "";
831
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
832
        // console.info(filterId, filterOp);
833
        for (let value of values) {
834
          countvalues++;
835
          var paramId = this.fieldIdsMap[filterId].param;
836
          // parameters+='&' + paramId+ '='+ value;//+"&" + this.fieldIdsMap[paramId].operator + "="+((countvalues == 1)?"and":"or");
837
          fq += (fq.length > 0 ? " " + filterOp + " " : "") + filterId + " exact " + (value);
838
        }
839
        if (countvalues > 0) {
840
          fq = "&fq=" + StringUtils.URIEncode(fq);
841
        }
842
        allFqs += fq;
843
      }
844
    }
845
    if (this.customFilter) {
846
      allFqs += "&fq=" + StringUtils.URIEncode(this.customFilter.queryFieldName + " exact " + StringUtils.quote((this.customFilter.valueId)));
847
    }
848

    
849
    if (this.quickFilter && this.entityType == "result") {
850
      if((firstLoad && URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)   || URLparams["qf"] == "true"
851
        || ((URLparams[this.quickFilter.filterId] != undefined && StringUtils.URIDecode(URLparams[this.quickFilter.filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1).indexOf(StringUtils.quote(this.quickFilter.value)) != -1))) {
852
        this.quickFilter.selected = true;
853
      } else {
854
        this.quickFilter.selected = false;
855
      }
856
      if ((firstLoad && URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)
857
      ||( URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == "true")) {
858
        allFqs += "&fq=resultbestaccessright exact " + StringUtils.quote(this.quickFilter.value);
859
      }
860
    }
861

    
862
    if (this.entityType == "result") {
863
      if (URLparams["type"]) {
864
        let types = URLparams["type"].split(",");
865
        if(types.indexOf("publications")!=-1 && types.indexOf("datasets")!=-1 && types.indexOf("software")!=-1 && types.indexOf("other")!=-1 ){
866
          allFqs += "&type=results";
867
        }else{
868
          for (let type of types) {
869
            allFqs += "&type=" + type;
870
          }
871
        }
872
      }else{
873
        allFqs += "&type=results";
874
      }
875
    } else if (this.entityType == "publication") {
876
      allFqs += "&type=publications";
877
    } else if (this.entityType == "dataset") {
878
      allFqs += "&type=datasets";
879
    } else if (this.entityType == "software") {
880
      allFqs += "&type=software";
881
    } else if (this.entityType == "other") {
882
      allFqs += "&type=other";
883
    } else if(this.entityType == "project") {
884
      allFqs += "&type=projects";
885
    } else if(this.entityType == "organization") {
886
      allFqs += "&type=organizations";
887
    } else if(this.entityType == "dataprovider") {
888
      allFqs += "&type=datasources";
889
    }
890
    // console.log("AllFqs (check type): "+allFqs);
891
    // console.log("type: "+this.entityType);
892
    // var keyword = URLparams['keyword'];
893
    // var doiQuery = "";
894
    // var keywordQuery = "";
895
    // if((keyword && keyword.length > 0)){
896
    //   if((this.type == 'publications' ||this.type == 'research data' || this.type == 'software' || this.type == 'other research products')){
897
    //     var DOIs:string[] = DOI.getDOIsFromString(keyword);
898
    //     var doisParams = "";
899
    //
900
    //     for(var i =0 ;i < DOIs.length; i++){
901
    //       doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
902
    //     }
903
    //     if(doisParams.length > 0){
904
    //       doiQuery += "&"+doisParams;
905
    //     }else {
906
    //       keywordQuery += "&q="+StringUtils.URIEncode(keyword);
907
    //     }
908
    //   }else{
909
    //     if(this.usedBy == "deposit") {
910
    //       if(this.keywordFields.length > 0) {
911
    //         keywordQuery = "&fq=";
912
    //       }
913
    //
914
    //       for(let i=0; i< this.keywordFields.length ; i++) {
915
    //         if(i > 0) {
916
    //           keywordQuery += " or ";
917
    //         }
918
    //         let field = this.keywordFields[i];
919
    //         //keywordQuery += field.name+field.equalityOperator+StringUtils.URIEncode(keyword);
920
    //         keywordQuery += field.name+field.equalityOperator+StringUtils.quote(StringUtils.URIEncode(keyword));
921
    //       }
922
    //     } else {
923
    //       keywordQuery += "&q=" + StringUtils.URIEncode(keyword);
924
    //     }
925
    //
926
    //   }
927
    // }
928
    //TODO add DOI?
929
     return allFqs;
930

    
931
  }
932

    
933
  /**
934
   * Create Search API query based on the filters of refine fields
935
   * @param URLparams
936
   */
937
  getSearchAPIQueryForRangeFields(URLparams) {
938
    let allFqs = "";
939
    for (let i = 0; i < this.rangeFields.length; i++) {
940
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
941
      let filterParam = this.searchFieldsHelper.getFieldParam(filterId, this.entityType);
942

    
943
      if (URLparams[filterParam] != undefined) {
944
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterParam]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
945
        var countvalues = 0;
946
        var fq = "";
947
        var fqFrom = "";
948
        var fqTo = "";
949
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
950

    
951
        for (let value of values) {
952
          if (this.fieldIdsMap[filterId].filterType == "range") {
953

    
954
            let selectedFromValue;
955
            let selectedToValue;
956

    
957
            let years: string[] = (value.substring(5)).split(":");
958
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
959
            //(Number.isInteger(parseInt(years[0], 10)) ? years[0] : null);
960
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
961
            //console.log("getSearchAPIQueryForRangeFields: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
962
            if(yearFrom) {
963
              selectedFromValue = yearFrom;
964
            }
965
            if(yearTo) {
966
              selectedToValue = yearTo;
967
            }
968
            if(yearFrom || yearTo) {
969

    
970
            // if (value.length <= 14) {
971
            //   if(Dates.isValidYear(value.substring(5, 9))) {
972
            //     selectedFromValue = value.substring(5, 9);
973
            //   }
974
            //   if(Dates.isValidYear(value.substring(10, 14))) {
975
            //     selectedToValue = value.substring(10, 14);
976
            //   }
977

    
978
              if(this.rangeFields[i][0] == this.rangeFields[i][1]) {
979
                //console.log(selectedFromValue + " - "+selectedToValue);
980
                if (selectedFromValue && selectedToValue) {
981
                  let equalityOp = this.fieldIdsMap[filterId].equalityOperator;
982
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + " " + selectedToValue + "\"";
983
                  fq = "&fq=" + StringUtils.URIEncode(fq);
984
                } else if (selectedFromValue) {
985
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
986
                  if(equalityOp == " = ") {
987
                    equalityOp = " >= ";
988
                  }
989
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + "\"";
990
                  fq = "&fq=" + StringUtils.URIEncode(fq);
991
                } else if (selectedToValue) {
992
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
993
                  if(equalityOp == " = ") {
994
                    equalityOp = " <= ";
995
                  }
996
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedToValue + "\"";
997
                  fq = "&fq=" + StringUtils.URIEncode(fq);
998
                }
999
              } else {
1000
                let equalityOpFrom = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
1001
                let equalityOpTo = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
1002

    
1003
                if (selectedFromValue) {
1004
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOpFrom + "\"" + selectedFromValue + "\"";
1005
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
1006
                }
1007
                if (selectedToValue) {
1008
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][1] + equalityOpTo + "\"" + selectedToValue + "\"";
1009
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
1010
                }
1011
                if(selectedFromValue || selectedToValue) {
1012
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1013
                }
1014
              }
1015
            }
1016
          }
1017
        }
1018
        allFqs += fq +fqFrom + fqTo;
1019
      }
1020
    }
1021

    
1022
    return allFqs;
1023

    
1024
  }
1025

    
1026
  /**
1027
   * Sets parameterNames and parameterValues arrays
1028
   * used in paging, advanced search link, Goto()
1029
   * @param filters either query filters or filters defined by the URL parameters
1030
   * @param rangeFilters defined by the URL parameters
1031
   * @param includePage
1032
   */
1033
  buildPageURLParameters(filters:Filter[], rangeFilters: RangeFilter[], includePage: boolean) {
1034
    this.parameterNames.splice(0, this.parameterNames.length);
1035
    this.parameterValues.splice(0, this.parameterValues.length);
1036
    for (var i = 0; i < this.selectedFields.length; i++) {
1037
      //default operator is and
1038
      this.parameterNames.push("f"+i);
1039
      this.parameterValues.push(this.selectedFields[i].id + (this.selectedFields[i].operatorId!='and'?(","+this.selectedFields[i].operatorId):''));
1040
      this.parameterNames.push("fv"+i);
1041
      if (this.selectedFields[i].type == "date") {
1042

    
1043
        if (this.selectedFields[i].dateValue.type == "range") {
1044
          this.parameterValues.push(StringUtils.URIEncode("range" + Dates.getDateToString(this.selectedFields[i].dateValue.from) + ":" + Dates.getDateToString(this.selectedFields[i].dateValue.to)));
1045
        } else {
1046
          this.parameterValues.push(StringUtils.URIEncode(this.selectedFields[i].dateValue.type));
1047
        }
1048

    
1049
      } else {
1050
        // console.log(this.selectedFields[i].value +" " + StringUtils.URIEncode(this.selectedFields[i].value))
1051
        this.parameterValues.push(StringUtils.URIEncode(this.selectedFields[i].value));
1052
      }
1053
    }
1054
    if (includePage && this.searchUtils.page != 1) {
1055
      this.parameterNames.push("page");
1056
      this.parameterValues.push("" + this.searchUtils.page);
1057
    }
1058

    
1059
    if (this.searchUtils.size != this.resultsPerPage) {
1060
      this.parameterNames.push("size");
1061
      this.parameterValues.push("" + this.searchUtils.size);
1062
    }
1063

    
1064
    if (this.sort && this.searchUtils.sortBy) {
1065
      this.parameterNames.push("sortBy");
1066
      this.parameterValues.push(this.searchUtils.sortBy);
1067
    }
1068
    for (let filter of filters) {
1069
      var filterLimits = "";
1070
      if (filter.countSelectedValues > 0) {
1071
        for (let value of filter.values) {
1072
          if (value.selected == true) {
1073
            filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + (value.id) + '"';
1074
          }
1075
        }
1076
        if (filterLimits.length > 0) {
1077
          this.parameterNames.push(filter.filterId);
1078
          this.parameterValues.push(filterLimits);
1079
        }
1080
      }
1081
    }
1082
    for (let filter of rangeFilters) {
1083
      var filterLimits = "";
1084
      let yearFrom: string = (Dates.isValidYear(filter.selectedFromValue) ? filter.selectedFromValue : null);
1085
      let yearTo: string = (Dates.isValidYear(filter.selectedToValue) ? filter.selectedToValue : null);
1086
      if(yearFrom || yearTo) {
1087
        this.parameterNames.push(filter.filterId);
1088
        this.parameterValues.push("range" + (yearFrom ? yearFrom : "") + ":" + (yearTo ? yearTo : ""));
1089
      }
1090
      // if (filter.countSelectedValues > 0) {
1091
      //   for (let value of filter.values) {
1092
      //     if (value.selected == true) {
1093
      //       filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + (value.id) + '"';
1094
      //     }
1095
      //   }
1096
      //   if (filterLimits.length > 0) {
1097
      //     this.parameterNames.push(filter.filterId);
1098
      //     this.parameterValues.push(filterLimits);
1099
      //   }
1100
      // }
1101
    }
1102
    if (this.searchUtils.keyword.length > 0) {
1103
      this.parameterNames.push("keyword");
1104
      this.parameterValues.push(this.searchUtils.keyword);
1105
    }
1106

    
1107
    if (this.resultTypes && this.entityType == "result") {
1108
      let values = [];
1109
      if (this.resultTypes.publication) {
1110
        values.push("publications");
1111
      }
1112
      if (this.resultTypes.dataset) {
1113
        values.push("datasets");
1114
      }
1115
      if (this.resultTypes.software) {
1116
        values.push("software");
1117
      }
1118
      if (this.resultTypes.other) {
1119
        values.push("other");
1120
      }
1121
      if (values.length > 0) {
1122
        this.parameterNames.push("type");
1123
        this.parameterValues.push(values.join(","));
1124
      }
1125
      if(this.quickFilter) {
1126
        this.parameterNames.push("qf");
1127
        this.parameterValues.push("" + this.quickFilter.selected);
1128
      }
1129
    }
1130

    
1131
    // if (this.searchUtils.size != this.resultsPerPage) {
1132
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'size=' + this.searchUtils.size;
1133
    //   this.parameterNames.push("size");
1134
    //   this.parameterValues.push("" + this.searchUtils.size);
1135
    // }
1136
    // if (this.sort && this.searchUtils.sortBy) {
1137
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'sortBy=' + this.searchUtils.sortBy;
1138
    //   this.parameterNames.push("sortBy");
1139
    //   this.parameterValues.push(this.searchUtils.sortBy);
1140
    // }
1141
    // console.log(this.parameterNames)
1142
    // console.log(this.parameterValues)
1143
  }
1144

    
1145
  /**
1146
   * create filters based on URL params
1147
   * @param URLparams
1148
   */
1149
  getRefineFiltersFromURL(URLparams) {
1150
    let fields = new SearchFields();
1151
    let filters: Filter[] = [];
1152
    for (let i = 0; i < this.refineFields.length; i++) {
1153
      let filterId = this.refineFields[i];
1154
      if (URLparams[filterId] != undefined) {
1155
        let filter = new Filter();
1156
        filter.title = fields.getFieldName(filterId, this.entityType);
1157
        filter.filterId = filterId;
1158
        filter.originalFilterId = filterId;
1159
        filter.values = [];
1160
        let values = StringUtils.URIDecode(URLparams[filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1161
        for (let value of values) {
1162

    
1163
          let v: Value = new Value();
1164
          v.name = RefineResultsUtils.keepPartAfterCharacters(StringUtils.unquote(value), "||");
1165
          v.id = StringUtils.unquote(value);
1166
          v.selected = true;
1167
          filter.values.push(v);
1168
          // console.log(v)
1169
          filter.countSelectedValues++;
1170
        }
1171
        filters.push(filter)
1172
      }
1173
    }
1174

    
1175
    if (this.quickFilter) {
1176
      if (this.entityType == "result" && (URLparams[this.quickFilter.filterId] == undefined) && (URLparams["qf"] == undefined || URLparams["qf"] == "true")) {
1177
        let filter = new Filter();
1178
        filter.title = fields.getFieldName(this.quickFilter.filterId, this.entityType);
1179
        filter.filterId = this.quickFilter.filterId;
1180
        filter.originalFilterId = this.quickFilter.filterId;
1181
        filter.values = [];
1182
        let v: Value = new Value();
1183
        v.name = this.quickFilter.value;
1184
        v.id = this.quickFilter.value;
1185
        v.selected = true;
1186
        filter.values.push(v);
1187
        filter.countSelectedValues = 1;
1188
        filters.push(filter)
1189
      }
1190
    }
1191
    if (this.entityType == "result") {
1192
      this.resultTypes = null;
1193
      this.resultTypes = {
1194

    
1195
      };
1196

    
1197
      if (URLparams["type"]) {
1198

    
1199
        this.resultTypes['publication'] = (URLparams["type"].split(",").indexOf("publications") != -1);
1200
        this.resultTypes['dataset'] = (URLparams["type"].split(",").indexOf("datasets") != -1);
1201
        this.resultTypes['software'] = (URLparams["type"].split(",").indexOf("software") != -1);
1202
        this.resultTypes['other'] = (URLparams["type"].split(",").indexOf("other") != -1);
1203

    
1204
      } else {
1205
        this.resultTypes['publication'] = true;
1206
        this.resultTypes['dataset'] = true;
1207
        this.resultTypes['software'] = true;
1208
        this.resultTypes['other'] = true;
1209
      }
1210

    
1211
    }
1212

    
1213
    this.URLCreatedFilters = filters;
1214
  }
1215

    
1216
  /**
1217
   * create range filters based on URL params
1218
   * @param URLparams
1219
   */
1220
  getRangeFiltersFromURL(URLparams) {
1221
    let fields = new SearchFields();
1222
    let filters: RangeFilter[] = [];
1223
    for (let i = 0; i < this.rangeFields.length; i++) {
1224
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
1225
      let filterParam = fields.getFieldParam(filterId, this.entityType);
1226
      //console.log("rangeFilter (from url): filterId - filterParam");
1227
      //console.log(filterId + " - "+ filterParam);
1228
      if (URLparams[filterParam] != undefined) {
1229
        let filter = new RangeFilter();
1230
        filter.title = fields.getFieldName(filterId, this.entityType);
1231
        filter.filterId = filterParam;
1232
        filter.originalFilterIdFrom = this.rangeFields[i][0];
1233
        filter.originalFilterIdTo = this.rangeFields[i][1];
1234

    
1235

    
1236
        let values = (decodeURIComponent(URLparams[filterParam])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1237
        for (let j = 0; j < values.length; j++) {
1238
          if (this.fieldIdsMap[filterId].filterType == "range") {
1239
            let value: string = StringUtils.unquote(values[j]);
1240
            let validDates: boolean = true;
1241
            // if (value.length < 14) {
1242
            //   validDates = false;
1243
            // } else {
1244
            //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
1245
            //     validDates = false;
1246
            //   } else {
1247
            //     filter.selectedFromValue = value.substring(5, 9);
1248
            //     filter.selectedToValue = value.substring(10, 14);
1249
            //   }
1250
            // }
1251
            let years: string[] = (value.substring(5)).split(":");
1252
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
1253
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
1254
            //console.log("getRangeFiltersFromURL: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
1255
            if(yearFrom) {
1256
              filter.selectedFromValue = yearFrom;
1257
              //filter.selectedFromAndToValues = yearFrom;
1258
            }
1259
            /*if(yearFrom && yearTo) {
1260
              filter.selectedFromAndToValues += "-";
1261
            }*/
1262
            if(yearTo) {
1263
              filter.selectedToValue = yearTo;
1264
              //filter.selectedFromAndToValues += yearTo;
1265
            }
1266
            //console.log("filter.selectedFromAndToValues: "+filter.selectedFromAndToValues);
1267
            if(!yearFrom && !yearTo) {
1268
              validDates = false;
1269
            }
1270

    
1271
          }
1272
        }
1273
        //console.log(filters);
1274
        filters.push(filter)
1275
      }
1276
    }
1277
    // console.log("Empty Filters");
1278
    // console.log(filters);
1279
    this.URLCreatedRangeFilters = filters;
1280
    // return filters;
1281

    
1282
  }
1283

    
1284
  /**
1285
   * Checks if query has no results, display Filters from URL parameters
1286
   * Mark checked  the selected filters
1287
   * Count the checked
1288
   * @param filters
1289
   */
1290
  public prepareFiltersToShow(filters: Filter[], totalResults): Filter[] {
1291
    if (this.URLCreatedFilters.length > 0 && totalResults == 0) {
1292
      this.showUnknownFilters = true;
1293
      this.filters = this.URLCreatedFilters;
1294
    } else if (totalResults != 0) {
1295
      this.showUnknownFilters = false;
1296
      this.filters = filters;
1297
    }
1298
    this.buildPageURLParameters(this.URLCreatedFilters, this.URLCreatedRangeFilters, true);
1299
    //this.checkSelectedRangeFilters(this.rangeFilters);
1300

    
1301
    this.checkSelectedFilters(this.filters);
1302
    this.countSelectedFilters(this.filters);
1303
    return this.filters;
1304
  }
1305

    
1306
  /**
1307
   * Mark checked  the selected range filters
1308
   */
1309
  public prepareRangeFiltersToShow() {
1310
    this.rangeFilters = RangeFilter.parse(this.rangeFields, this.entityType); // OK
1311

    
1312
    //this.buildPageURLRangeParameters(this.rangeFilters, true);
1313
    this.checkSelectedRangeFilters(this.rangeFilters);
1314
    this.countSelectedRangeFilters(this.rangeFilters);
1315
    return this.rangeFilters;
1316
  }
1317

    
1318
  /**
1319
   * Used to set the variables and search page, and prepare it before the getResults query
1320
   * @param fieldIds
1321
   * @param selectedFields
1322
   * @param refineFields
1323
   * @param rangeFields
1324
   * @param fieldIdsMap
1325
   * @param customFilter
1326
   * @param params
1327
   * @param entityType
1328
   * @param quickFilter
1329
   */
1330
  prepareSearchPage(fieldIds, selectedFields, refineFields, rangeFields, fieldIdsMap, customFilter, params, entityType, quickFilter=null){
1331
    // console.log(this.refineFields);
1332
    this.entityType = entityType;
1333
    this.fieldIds = fieldIds;
1334
    this.selectedFields = selectedFields;
1335
    this.refineFields = refineFields;
1336
    this.rangeFields = rangeFields;
1337
    this.fieldIdsMap = fieldIdsMap;
1338
    this.customFilter = customFilter;
1339
    this.quickFilter = quickFilter;
1340
    this.getRangeFiltersFromURL(params);
1341
    this.getRefineFiltersFromURL(params);
1342
    this.createAdvancedSearchSelectedFiltersFromURLParameters(params);
1343
  }
1344
}
(20-20/55)