Project

General

Profile

1
import {Component, 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, DOI, 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

    
21
@Component({
22
  selector: 'new-search-page',
23
  templateUrl: 'newSearchPage.component.html'
24
})
25
export class NewSearchPageComponent {
26
  @Input() piwikSiteId = null;
27
  @Input() hasPrefix: boolean = true;
28
  @Input() pageTitle = "";
29
  @Input() results = [];
30
  @Input() type;
31
  @Input() entityType;
32
  @Input() searchUtils: SearchUtilsClass = new SearchUtilsClass();
33
  @Input() fieldIds: string[];
34
  @Input() fieldIdsMap;//:{ [key:string]:{ name:string, operator:string, type:string, indexField:string, equalityOperator:string  }} ;
35
  @Input() selectedFields: AdvancedField[];
36
  @ViewChild(ModalLoading) loading: ModalLoading;
37
  @Input() csvParams: string;
38
  @Input() csvPath: string;
39
  @Input() simpleSearchLink: string = "";
40
  @Input() advancedSearchLink: string = "";
41
  @Input() disableForms: boolean = false;
42
  @Input() loadPaging: boolean = true;
43
  @Input() oldTotalResults: number = 0;
44
  @Input() openaireLink: string;
45
  @Input() customFilter: SearchCustomFilter = null;
46
  @Input() sort: boolean = false;
47
  @Input() searchFormClass: string = "searchForm";
48
  //From simple:
49
  @Input() rangeFilters: RangeFilter[] = [];
50
  @Input() rangeFields: string[][] = [];
51
  @Input() refineFields = [];
52
  @Input() filters = [];
53
  selectedFilters: number = 0;
54
  selectedRangeFilters: number = 0;
55
  private searchFieldsHelper: SearchFields = new SearchFields();
56
  @Input() newQueryButton: boolean = true;
57
  public showUnknownFilters: boolean = false; // when a filter exists in query but has no results, so no filters returned from the query
58
  URLCreatedFilters: Filter[] = [];
59
  URLCreatedRangeFilters: RangeFilter[] = [];
60
  @Input() showRefine: boolean = true;
61
  @Input() tableViewLink: string;
62
  @Input() usedBy: string = "search";
63
  @Input() showResultCount: boolean = true;
64
  @Input() showMoreFilterValuesInline: boolean = true;
65
  @Input() filterValuesNum: number = 6;
66
  @Input() keywordFields = [];
67
  @Input() simpleView: boolean = true;
68
  @Input() formPlaceholderText = "Type Keywords...";
69
  @Input() resultTypes = null;
70
  @Input() quickFilter: { filter: Filter, selected: boolean, filterId: string, value: string };
71
  @Input() includeOnlyResultsAndFilter:boolean = false;
72
  piwiksub: any;
73
  public parameterNames: string[] = [];
74
  public parameterValues: string[] = [];
75

    
76
  public csvLimit: number = 0;
77
  public pagingLimit: number = 0;
78
  public resultsPerPage: number = 0;
79
  isPiwikEnabled = false;
80
  properties: EnvProperties;
81
  public pageContents = null;
82
  public divContents = null;
83
  public routerHelper: RouterHelper = new RouterHelper();
84
  public errorCodes: ErrorCodes = new ErrorCodes();
85

    
86
  url = null;
87

    
88
  @Input() entitiesSelection:boolean = true;
89
  @Input() showAdvancedSearchLink:boolean = true;
90
  constructor(private route: ActivatedRoute,
91
              private location: Location,
92
              private _meta: Meta,
93
              private _title: Title,
94
              private _piwikService: PiwikService,
95
              private router: Router,
96
              private seoService: SEOService,
97
              private helper: HelperService) {
98
  }
99

    
100
  ngOnInit() {
101
    this.route.data
102
      .subscribe((data: { envSpecific: EnvProperties }) => {
103
        this.properties = data.envSpecific;
104
        //this.getDivContents();
105
        this.getPageContents();
106
        this.pagingLimit = data.envSpecific.pagingLimit;
107
        this.resultsPerPage = data.envSpecific.resultsPerPage;
108
        this.csvLimit = data.envSpecific.csvLimit;
109
        this.isPiwikEnabled = data.envSpecific.enablePiwikTrack;
110
        if (typeof window !== 'undefined') {
111
          this.updateUrl(data.envSpecific.baseLink + location.pathname);
112
          this.url = data.envSpecific.baseLink + location.pathname
113
        }
114
        if (typeof document !== 'undefined' && this.isPiwikEnabled) {
115
          this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe();
116
        }
117
      });
118

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

    
121
    this.updateTitle(this.pageTitle);
122
    this.updateDescription(description);
123

    
124
    this.searchUtils.baseUrl = "/" + this.searchUtils.baseUrl;
125
    this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.router.url, false);
126

    
127

    
128
  }
129

    
130
  private getPageContents() {
131
    this.helper.getPageHelpContents(this.router.url, this.properties, (this.customFilter) ? this.customFilter.valueId : null).subscribe(contents => {
132

    
133
      this.pageContents = contents;
134
    })
135
  }
136

    
137
  private getDivContents() {
138
    this.helper.getDivHelpContents(this.router.url, this.properties, (this.customFilter) ? this.customFilter.valueId : null).subscribe(contents => {
139
      this.divContents = contents;
140
    })
141
  }
142

    
143
  ngOnDestroy() {
144
    if (this.piwiksub) {
145
      this.piwiksub.unsubscribe();
146
    }
147
  }
148

    
149
  updateDescription(description: string) {
150
    this._meta.updateTag({content: description}, "name='description'");
151
    this._meta.updateTag({content: description}, "property='og:description'");
152
  }
153

    
154
  updateTitle(title: string) {
155
    var _prefix = "";
156
    if (this.hasPrefix) {
157
      _prefix = "OpenAIRE | ";
158
    }
159
    var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title);
160
    this._title.setTitle(_title);
161
    this._meta.updateTag({content: _title}, "property='og:title'");
162
  }
163

    
164
  updateUrl(url: string) {
165
    this._meta.updateTag({content: url}, "property='og:url'");
166
  }
167

    
168

    
169
  clearFilters() {
170
    for (var i = 0; i < this.filters.length; i++) {
171
      for (var j = 0; j < this.filters[i].countSelectedValues; j++) {
172
        if (this.filters[i].values[j].selected) {
173
          this.filters[i].values[j].selected = false;
174
        }
175
        this.filters[i].countSelectedValues = 0;
176
      }
177
    }
178
    this.selectedFilters = 0;
179
    for(let i = 0; i < this.rangeFilters.length; i++) {
180
      this.rangeFilters[i].selectedFromValue = null;
181
      this.rangeFilters[i].selectedToValue = null;
182
    }
183
    this.selectedRangeFilters = 0;
184
    if (this.quickFilter) {
185
      this.removeValueFromQuickFilter();
186
    }
187
    this.goTo(1);
188
    // this.clearKeywords();
189
  }
190

    
191
  goTo(page: number = 1) {
192
    this.searchUtils.page = page;
193
    this.buildPageURLParameters(this.filters, this.rangeFilters, true);
194
    this.router.navigate([this.searchUtils.baseUrl], {queryParams: this.routerHelper.createQueryParams(this.parameterNames, this.parameterValues)});
195
    /* Code For Piwik*/
196
    if (typeof localStorage !== 'undefined') {
197
      //console.log("In PreviousRouteRecorder : "+this.router.url );
198
      localStorage.setItem('previousRoute', this.router.url);
199
    }
200
    if (this.isPiwikEnabled && (typeof document !== 'undefined')) {
201
      this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe();
202
    }
203
    /* End Piwik Code */
204
  }
205

    
206
  queryChanged() {
207

    
208
    this.goTo(1);
209
  }
210

    
211

    
212
  sizeChanged($event) {
213
    this.searchUtils.size = $event.value;
214
    this.goTo(1);
215
  }
216

    
217
  sortByChanged($event) {
218
    this.searchUtils.sortBy = $event.value;
219
    this.goTo(1);
220
  }
221

    
222

    
223
  getOperatorParameter(parameter: string): string {
224
    for (let id of this.fieldIds) {
225
      if (this.fieldIdsMap[id]["param"] == parameter) {
226
        return this.fieldIdsMap[id]["operator"];
227
      }
228
    }
229
  }
230

    
231
  /*
232
* Get A sub-array of this.refineFields array, which contains the ids of the selected filters
233
*/
234
  public getSelectedFilters(): string[] {
235
    var selected: string[] = [];
236
    for (var i = 0; i < this.filters.length; i++) {
237
      var filter: Filter = this.filters[i];
238
      if (filter.countSelectedValues > 0) {
239
        selected.push(filter.filterId);
240
      }
241
    }
242
    return selected;
243
  }
244

    
245
  /*
246
    * Get A sub-array of this.refineFields array, which contains the ids of the selected parameters
247
    */
248
  private getSelectedParameters(): string[] {
249
    var selected: string[] = [];
250
    for (var i = 0; i < this.refineFields.length; i++) {
251
      if (this.parameterNames.indexOf(this.refineFields[i]) != -1) {
252
        selected.push(this.refineFields[i]);
253
      }
254
    }
255
    return selected;
256
  }
257

    
258
  /*
259
  * 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 )
260
  */
261
  public getFields(): string[] {
262
    var selected_filters: string[] = this.getSelectedFilters();
263
    if (selected_filters.length == 0) {
264
      selected_filters = this.getSelectedParameters();
265
    }
266
    var fields: string[] = [];
267
    for (var i = 0; i < this.refineFields.length; i++) {
268
      var dependentTo = this.searchFieldsHelper.DEPENDENT_FIELDS[this.refineFields[i]];
269

    
270
      //if filter is not marked as hidden OR it is hidden but it is dependent to a field that it IS selected
271
      if (this.searchFieldsHelper.HIDDEN_FIELDS.indexOf(this.refineFields[i]) == -1 || (selected_filters.indexOf(dependentTo) != -1) || (selected_filters.indexOf(this.refineFields[i]) != -1)) {
272
        fields.push(this.refineFields[i]);
273
      }
274
    }
275
    return fields;
276
  }
277

    
278
  /*
279
  * Get a query  string of all fields, that want to get from search (e.g. &fields=funderid&fields=projectstartyear&...))
280
  */
281
  public getRefineFieldsQuery(): string {
282

    
283
    var fields: string[] = this.getFields();
284
    var fieldsStr = ""
285
    for (var i = 0; i < fields.length; i++) {
286
      fieldsStr += "&fields=" + fields[i];
287
    }
288
    return "&refine=true" + fieldsStr;
289
  }
290

    
291

    
292
  /*
293
  * Mark as check the new filters that are selected, when you get them from search
294
  */
295
  public checkSelectedFilters(filters: Filter[]) {
296
    this.filters = filters;
297
    for (var i = 0; i < filters.length; i++) {
298
      var filter: Filter = filters[i];
299
      filter.countSelectedValues = 0;
300
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
301
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
302
        for (let filterValue of filter.values) {
303
          if (values.indexOf(StringUtils.quote(filterValue.id)) > -1) {
304
            filterValue.selected = true;
305
            filter.countSelectedValues++;
306
          } else {
307
            filterValue.selected = false;
308

    
309
          }
310
        }
311
      } else if (this.quickFilter && this.quickFilter.filterId == filter.filterId && this.quickFilter.selected) {
312
        for (let filterValue of filter.values) {
313
          if (filterValue.id == this.quickFilter.value) {
314
            filterValue.selected = true;
315
            filter.countSelectedValues++;
316
          } else {
317
            filterValue.selected = false;
318
          }
319
        }
320
      } else {
321
        for (let filterValue of filter.values) {
322
          filterValue.selected = false;
323
        }
324
      }
325
      if (this.quickFilter && filter.filterId == this.quickFilter.filterId) {
326
        this.quickFilter.filter = filter;
327
      }
328
    }
329
    this.filterFilterValues(this.filters);
330
    return filters;
331
  }
332

    
333
  /*
334
* Mark as check the new range filters that are selected
335
*/
336
  public checkSelectedRangeFilters(filters: RangeFilter[]) {
337
    //console.log("checkSelectedRangeFilters: parameterNames.length: "+this.parameterNames.length);
338

    
339
    this.rangeFilters = filters;
340
    for (let i = 0; i < filters.length; i++) {
341
      let filter: RangeFilter = filters[i];
342

    
343
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
344
        //console.log(filter.filterId + " "+this.parameterNames.indexOf(filter.filterId) );
345
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
346
        let operators: string [] = (StringUtils.URIDecode(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
347
        if (values.length == operators.length) {
348
          for (let j = 0; j < values.length; j++) {
349
            if (this.fieldIdsMap[filter.originalFilterIdFrom+"-range-"+filter.originalFilterIdTo].filterType == "range") {
350
              let value: string = StringUtils.unquote(values[j]);
351
              let validDates: boolean = true;
352

    
353
              let years: string[] = (value.substring(5)).split(":");
354
              let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
355
              let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
356
              //console.log("checkSelectedRangeFilters: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
357
              if(yearFrom) {
358
                filter.selectedFromValue = yearFrom;
359
              }
360
              if(yearTo) {
361
                filter.selectedToValue = yearTo;
362
              }
363
              if(yearFrom && yearTo) {
364
                filter.selectedFromAndToValues = yearFrom + "-" + yearTo;
365
              } else if(yearFrom) {
366
                filter.selectedFromAndToValues = "From " + yearFrom;
367
              } else if(yearTo) {
368
                filter.selectedFromAndToValues = "Until " + yearTo;
369
              }
370

    
371
              if(!yearFrom && !yearTo) {
372
                validDates = false;
373
              }
374

    
375
              // if (value.length < 14) {
376
              //   validDates = false;
377
              //   console.log("not valid (length<14)");
378
              // } else {
379
              //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
380
              //     validDates = false;
381
              //     console.log("not valid years");
382
              //   } else {
383
              //     filter.selectedFromValue = value.substring(5, 9);
384
              //     filter.selectedToValue = value.substring(10, 14);
385
              //     console.log(filter);
386
              //   }
387
              // }
388
            }
389
          }
390
        }
391
      } else {
392
        filter.selectedFromValue = null;
393
        filter.selectedToValue = null;
394
      }
395
    }
396
    return this.rangeFilters;
397
  }
398

    
399
  /*
400
  * For Funder filters - if funder selected
401
  */
402
  public filterFilterValues(filters: Filter[]) {
403
    var funders = [];
404
    var funder_prefix = [];
405
    for (var i = 0; i < filters.length; i++) {
406

    
407
      var filter: Filter = filters[i];
408
      //  console.log(filter.filterId);
409
      if (filter.filterId.indexOf("funder") != -1 && this.parameterNames.indexOf(filter.filterId) != -1) {
410
        let funders = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
411
        for (let funder of funders) {
412
          funder_prefix.push(StringUtils.unquote(funder).split("____")[0]);
413
        }
414
        //  console.log(funder_prefix );
415
      } else if (filter.filterId.indexOf("funding") != -1) {
416
        //  console.log(" funding: "+filter.filterId );
417
        var filteredValues = []
418
        for (let filterValue of filter.values) {
419
          var value_prefix = filterValue.id.split("____")[0];
420
          //  console.log("Value prefix: "+value_prefix );
421
          if (funder_prefix.indexOf(value_prefix) != -1) {
422
            //  console.log("here" + value_prefix);
423
            filteredValues.push(filterValue);
424
          }
425

    
426
        }
427
        if (filteredValues.length > 0) {
428
          filter.values = filteredValues;
429
        }
430
      }
431

    
432
    }
433

    
434
    return filters;
435
  }
436

    
437
  public countSelectedFilters(filters: Filter[]): number {
438
    this.selectedFilters = 0;
439
    for (let filter of filters) {
440
      if (filter.countSelectedValues > 0) {
441
        this.selectedFilters += filter.countSelectedValues;
442
      }
443
    }
444
    return this.selectedFilters;
445
  }
446

    
447
  public countSelectedRangeFilters(rangeFilters: RangeFilter[]) : number {
448
    this.selectedRangeFilters = 0;
449
    for(let filter of rangeFilters) {
450
      if(filter.selectedFromValue || filter.selectedToValue) {
451
        this.selectedRangeFilters++;
452
      }
453
    }
454
    return this.selectedRangeFilters;
455
  }
456

    
457
  private clearKeywords() {
458
    if (this.searchUtils.keyword.length > 0) {
459
      this.searchUtils.keyword = '';
460
    }
461
    this.goTo(1);
462
  }
463

    
464
  public removeFilter(value: Value, filter: Filter) {
465
    filter.countSelectedValues--;
466
    this.selectedFilters--;
467
    if (value.selected == true) {
468
      value.selected = false;
469
    }
470
    if (this.quickFilter && this.quickFilter.filterId == filter.filterId) {
471
      this.removeValueFromQuickFilter();
472
    }
473
    this.goTo(1);
474
  }
475

    
476
  public removeRangeFilter(filter: RangeFilter) {
477
    filter.selectedFromValue = null;
478
    filter.selectedToValue = null;
479
    this.goTo(1);
480
  }
481

    
482
  getSelectedValues(filter): any {
483
    var selected = [];
484
    if (filter.countSelectedValues > 0) {
485
      for (var i = 0; i < filter.values.length; i++) {
486
        if (filter.values[i].selected) {
487
          selected.push(filter.values[i]);
488
        }
489
      }
490
    }
491
    return selected;
492

    
493
  }
494

    
495
  filterChanged($event) {
496
    if (this.quickFilter && this.quickFilter.filter) {
497
      this.removeValueFromQuickFilter();
498
    }
499
    this.goTo(1);
500

    
501
  }
502

    
503
  /**
504
   * if there is a change in the values of the quick filter, this function has to be run, to also update the quickFilter
505
   */
506
  removeValueFromQuickFilter() {
507
    if (this.quickFilter.filter.countSelectedValues == 0) {
508
      this.quickFilter.selected = false;
509
    } else {
510
      let isQuickEnabled = false;
511
      for (let filterValue of this.quickFilter.filter.values) {
512
        isQuickEnabled = (filterValue.name == this.quickFilter.value)
513
      }
514
      this.quickFilter.selected = (isQuickEnabled && this.quickFilter.filter.countSelectedValues == 1);
515
    }
516
  }
517

    
518
  // for loading
519
  public openLoading() {
520
    this.loading.open();
521
  }
522

    
523
  public closeLoading() {
524
    this.loading.close();
525
  }
526

    
527
  /**
528
   * Build advanced search Filters based on the URL parameters
529
   * @param params
530
   */
531
  createAdvancedSearchSelectedFiltersFromURLParameters(params) {
532
    for (var i = 0; i < this.fieldIds.length; i++) {
533

    
534
      var fieldId = this.fieldIds[i];
535
      var fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
536
      if (!this.fieldIdsMap[fieldId]) {
537

    
538
        console.error("Field: " + fieldId + " not found in fieldIds map");
539
      }
540

    
541
      var operatorId = this.getOperatorParameter(fieldparam);
542
      if (params[fieldparam] != undefined && params[operatorId] != undefined) {
543
        var values: string [] = StringUtils.URIDecode(params[fieldparam]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
544
        var operators: string [] = (StringUtils.URIDecode(params[operatorId])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
545
        if (values.length == operators.length) {
546
          for (var j = 0; j < values.length; j++) {
547
            if (this.fieldIdsMap[fieldId].type == "date") {
548
              var value: string = StringUtils.unquote(values[j]);
549
              var validDates: boolean = true;
550
              var dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operators[j]);
551
              if (value.indexOf("range") != -1) {
552
                dateField.dateValue.type = "range";
553
                if (value.length < 26) {
554
                  validDates = false;
555
                } else {
556
                  if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
557
                    validDates = false;
558
                  } else {
559
                    dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
560
                    dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
561
                  }
562
                }
563
                //  "rangeYYYY-MM-DD:YYYY-MM-DD"
564
              } else {
565
                dateField.dateValue.setDatesByType(value);
566
              }
567
              if (validDates) {
568
                this.selectedFields.push(dateField);
569
              }
570

    
571
            } else {
572
              this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, StringUtils.unquote(values[j]), operators[j]));
573
            }
574
          }
575
        }
576
      }
577
    }
578
    if (params['keyword'] && params['keyword'].length > 0) {
579
      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"));
580
    }
581
    if (this.selectedFields.length == 0) {
582
      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"));
583
    }
584
  }
585

    
586
  /**
587
   * Create Search API query based on the selected fields of the advanced form
588
   */
589
  getSearchAPIQueryForAdvancedSearhFields() {
590

    
591
    var params = "";
592
    var countParams = 0;
593
    for (var i = 0; i < this.selectedFields.length; i++) {
594
      if (this.fieldIdsMap[this.selectedFields[i].id] != undefined && (this.selectedFields[i].value != "" || this.selectedFields[i].type == "date")) {
595
        //console.log("createQueryParameters::"+this.selectedFields[i].type);
596
        if (this.selectedFields[i].type == "date") {
597
          if (this.selectedFields[i].dateValue.type != "any") {
598
            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)) + " "
599
              + StringUtils.URIEncode(Dates.getDateToString(this.selectedFields[i].dateValue.to)) + '"' + " ";
600
          }
601
        } else {
602
          if (this.selectedFields[i].id == "q") {
603
            var op = "";
604
            var doisParams = "";
605
            if ((this.type == 'publications' || this.type == 'research data' || this.type == 'software' || this.type == 'other research products')) { //
606
              var DOIs: string[] = DOI.getDOIsFromString(this.selectedFields[i].value);
607
              for (var i = 0; i < DOIs.length; i++) {
608
                doisParams += (doisParams.length > 0 ? " or " : "") + 'pid="' + DOIs[i] + '"';
609
              }
610
            }
611
            if (doisParams.length > 0) {
612
              params += doisParams;
613
            } else {
614
              //Remove quotes from keyword search
615
              // params += (countParams == 0 ? "" : this.selectedFields[i].operatorId) + " " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
616
              // params += (countParams == 0 ? "" : this.selectedFields[i].operatorId) + " " + StringUtils.URIEncode(this.selectedFields[i].value) + " ";
617
              params += this.createQuotedKeywordQuery(this.selectedFields[i],countParams,true);
618
            }
619
            // params += (countParams == 0 ? "" : this.selectedFields[i].operatorId) + " " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
620
          } else if (countParams == 0 && this.selectedFields[i].operatorId == "not" && this.fieldIdsMap[this.selectedFields[i].id].equalityOperator != "=") {
621
            params += " " + this.selectedFields[i].id + " <> " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
622
          } else if(this.fieldIdsMap[this.selectedFields[i].id].equalityOperator == "=") {
623
            params+=this.createQuotedKeywordQuery(this.selectedFields[i], countParams, false);
624
          }else{
625
              params += (countParams == 0 ? "" : this.selectedFields[i].operatorId + " ") + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + encodeURIComponent(this.selectedFields[i].value) + '"' + " ";
626

    
627
          }
628
        }
629
        countParams++;
630
      }
631
    }
632

    
633
    if (this.customFilter) {
634
      params += (countParams == 0 ? "" : " and ") + this.customFilter.queryFieldName + " exact " + StringUtils.quote((this.customFilter.valueId));
635
    }
636
    console.log("ParameterS:")
637
    console.log(params)
638
    return params;
639
  }
640

    
641
  createQuotedKeywordQuery(field:AdvancedField, countParams:number, isSearchAll:boolean){
642
    console.log(field)
643
    let params = "";
644
    let quotedParts = (field.value)?field.value.match(/(["'])(.*?)*?\1/g):[];
645
    console.log(quotedParts)
646
    params+= (countParams == 0 ? "" : field.operatorId) + " (";
647
    if(quotedParts && quotedParts.length == 1 && quotedParts[0] == field.value ){
648
      params+=this.getQuotedQueryPart(field.id, field.value,isSearchAll);
649
    }else if( quotedParts && quotedParts.length > 0){
650
      for(let i=0; i< quotedParts.length; i++){
651
        params+=(i>0)?" and ":"";
652
        params+=this.getQuotedQueryPart(field.id, quotedParts[i],isSearchAll);
653
      }
654
      let startPoint = 0;
655
      let endPoint = 0;
656
      for(let i=0; i< quotedParts.length; i++){
657
        let index = field.value.indexOf(quotedParts[i]);
658
        endPoint = (i+1<quotedParts.length)? field.value.indexOf(quotedParts[i+1]):field.value.length;
659
        // console.log(field.value.indexOf(quotedParts[i+1]) +" - "+field.value.length);
660
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
661
        if(index==startPoint){
662
          startPoint +=quotedParts[i].length;
663
        }else if(startPoint < index){
664
          endPoint = index;
665
        }
666
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
667
        if(decodeURIComponent(field.value.substring(startPoint,endPoint)).split(" ").join("").length > 0) {
668
          params += " and " + this.getNoQuotedQueryPart(field.id, field.value.substring(startPoint, endPoint), isSearchAll);
669
        }
670
        // console.log("For "+i+"  " +params+" SP "+ startPoint+" EP: "+endPoint);
671
        // startPoint = (i+1<quotedParts.length)? field.value.indexOf(quotedParts[i+i]):field.value.length;//(startPoint<index  )?(index + quotedParts[i].length):field.value.length;
672
        startPoint = ((i+1<quotedParts.length)?(field.value.indexOf(quotedParts[i+1])+quotedParts[i+1].length):(endPoint== index?(index+quotedParts[i].length):endPoint));
673
        console.log(" Next SP "+ startPoint);
674
      }
675
      if(startPoint !=field.value.length && decodeURIComponent(field.value.substring(startPoint,field.value.length)).split(" ").join("").length > 0){
676
        params+=" and " + this.getNoQuotedQueryPart(field.id, field.value.substring(startPoint,field.value.length),isSearchAll);
677
      }
678
    }else{
679
      params+=this.getNoQuotedQueryPart(field.id, field.value,isSearchAll);
680
    }
681
    params += " )";
682
    return params;
683
  }
684

    
685
  private getQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
686
      return " ("+(isSearchAll?"__all":fieldId)+" exact "+StringUtils.URIEncode(value)+")";
687
  }
688
  private getNoQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
689
    if(isSearchAll){
690
      return " (" + value + ")"
691
    }else{
692
      return " ("+fieldId+"="+ StringUtils.URIEncode(value)+")";
693
    }
694
  }
695

    
696
  /**
697
   * Create Search API query based on the filters of refine fields
698
   * @param URLparams
699
   * @param firstLoad
700
   */
701
  getSearchAPIQueryForRefineFields(URLparams, firstLoad: boolean) {
702

    
703
    var allFqs = "";
704
    for (var i = 0; i < this.refineFields.length; i++) {
705
      var filterId = this.refineFields[i];
706

    
707
      if (URLparams[filterId] != undefined) {
708
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterId]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
709
        var countvalues = 0;
710
        var fq = "";
711
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
712
        // console.info(filterId, filterOp);
713
        for (let value of values) {
714
          countvalues++;
715
          var paramId = this.fieldIdsMap[filterId].param;
716
          // parameters+='&' + paramId+ '='+ value;//+"&" + this.fieldIdsMap[paramId].operator + "="+((countvalues == 1)?"and":"or");
717
          fq += (fq.length > 0 ? " " + filterOp + " " : "") + filterId + " exact " + (value);
718
        }
719
        if (countvalues > 0) {
720
          fq = "&fq=" + StringUtils.URIEncode(fq);
721
        }
722
        allFqs += fq;
723
      }
724
    }
725
    if (this.customFilter) {
726
      allFqs += "&fq=" + StringUtils.URIEncode(this.customFilter.queryFieldName + " exact " + StringUtils.quote((this.customFilter.valueId)));
727
    }
728

    
729
    if (this.quickFilter && this.entityType == "result") {
730
      if((firstLoad && URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)   || URLparams["qf"] == "true"
731
        || ((URLparams[this.quickFilter.filterId] != undefined && StringUtils.URIDecode(URLparams[this.quickFilter.filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1).indexOf(StringUtils.quote(this.quickFilter.value)) != -1))) {
732
        this.quickFilter.selected = true;
733
      } else {
734
        this.quickFilter.selected = false;
735
      }
736
      if ((firstLoad && URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)
737
      ||( URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == "true")) {
738
        allFqs += "&fq=resultbestaccessright exact " + StringUtils.quote(this.quickFilter.value);
739
      }
740
    }
741

    
742
    if (this.entityType == "result") {
743
      if (URLparams["type"]) {
744
        for (let type of URLparams["type"].split(",")) {
745
          allFqs += "&type=" + type;
746
        }
747
      }else{
748
        allFqs += "&type=publications&type=datasets&type=software&type=other";
749
      }
750
    } else if (this.entityType == "publication") {
751
      allFqs += "&type=publications";
752
    } else if (this.entityType == "dataset") {
753
      allFqs += "&type=datasets";
754
    } else if (this.entityType == "software") {
755
      allFqs += "&type=software";
756
    } else if (this.entityType == "other") {
757
      allFqs += "&type=other";
758
    } else if(this.entityType == "project") {
759
      allFqs += "&type=projects";
760
    } else if(this.entityType == "organization") {
761
      allFqs += "&type=organizations";
762
    } else if(this.entityType == "dataprovider") {
763
      allFqs += "&type=datasources";
764
    }
765
    console.log("AllFqs (check type): "+allFqs);
766
    console.log("type: "+this.entityType);
767
    // var keyword = URLparams['keyword'];
768
    // var doiQuery = "";
769
    // var keywordQuery = "";
770
    // if((keyword && keyword.length > 0)){
771
    //   if((this.type == 'publications' ||this.type == 'research data' || this.type == 'software' || this.type == 'other research products')){
772
    //     var DOIs:string[] = DOI.getDOIsFromString(keyword);
773
    //     var doisParams = "";
774
    //
775
    //     for(var i =0 ;i < DOIs.length; i++){
776
    //       doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
777
    //     }
778
    //     if(doisParams.length > 0){
779
    //       doiQuery += "&"+doisParams;
780
    //     }else {
781
    //       keywordQuery += "&q="+StringUtils.URIEncode(keyword);
782
    //     }
783
    //   }else{
784
    //     if(this.usedBy == "deposit") {
785
    //       if(this.keywordFields.length > 0) {
786
    //         keywordQuery = "&fq=";
787
    //       }
788
    //
789
    //       for(let i=0; i< this.keywordFields.length ; i++) {
790
    //         if(i > 0) {
791
    //           keywordQuery += " or ";
792
    //         }
793
    //         let field = this.keywordFields[i];
794
    //         //keywordQuery += field.name+field.equalityOperator+StringUtils.URIEncode(keyword);
795
    //         keywordQuery += field.name+field.equalityOperator+StringUtils.quote(StringUtils.URIEncode(keyword));
796
    //       }
797
    //     } else {
798
    //       keywordQuery += "&q=" + StringUtils.URIEncode(keyword);
799
    //     }
800
    //
801
    //   }
802
    // }
803
    //TODO add DOI?
804
     return allFqs;
805

    
806
  }
807

    
808
  /**
809
   * Create Search API query based on the filters of refine fields
810
   * @param URLparams
811
   */
812
  getSearchAPIQueryForRangeFields(URLparams) {
813
    let allFqs = "";
814
    for (let i = 0; i < this.rangeFields.length; i++) {
815
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
816
      let filterParam = this.searchFieldsHelper.getFieldParam(filterId, this.entityType);
817

    
818
      if (URLparams[filterParam] != undefined) {
819
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterParam]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
820
        var countvalues = 0;
821
        var fq = "";
822
        var fqFrom = "";
823
        var fqTo = "";
824
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
825

    
826
        for (let value of values) {
827
          if (this.fieldIdsMap[filterId].filterType == "range") {
828

    
829
            let selectedFromValue;
830
            let selectedToValue;
831

    
832
            let years: string[] = (value.substring(5)).split(":");
833
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
834
            //(Number.isInteger(parseInt(years[0], 10)) ? years[0] : null);
835
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
836
            //console.log("getSearchAPIQueryForRangeFields: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
837
            if(yearFrom) {
838
              selectedFromValue = yearFrom;
839
            }
840
            if(yearTo) {
841
              selectedToValue = yearTo;
842
            }
843
            if(yearFrom || yearTo) {
844

    
845
            // if (value.length <= 14) {
846
            //   if(Dates.isValidYear(value.substring(5, 9))) {
847
            //     selectedFromValue = value.substring(5, 9);
848
            //   }
849
            //   if(Dates.isValidYear(value.substring(10, 14))) {
850
            //     selectedToValue = value.substring(10, 14);
851
            //   }
852

    
853
              if(this.rangeFields[i][0] == this.rangeFields[i][1]) {
854
                //console.log(selectedFromValue + " - "+selectedToValue);
855
                if (selectedFromValue && selectedToValue) {
856
                  let equalityOp = this.fieldIdsMap[filterId].equalityOperator;
857
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + " " + selectedToValue + "\"";
858
                  fq = "&fq=" + StringUtils.URIEncode(fq);
859
                } else if (selectedFromValue) {
860
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
861
                  if(equalityOp == " = ") {
862
                    equalityOp = " >= ";
863
                  }
864
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + "\"";
865
                  fq = "&fq=" + StringUtils.URIEncode(fq);
866
                } else if (selectedToValue) {
867
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
868
                  if(equalityOp == " = ") {
869
                    equalityOp = " <= ";
870
                  }
871
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedToValue + "\"";
872
                  fq = "&fq=" + StringUtils.URIEncode(fq);
873
                }
874
              } else {
875
                let equalityOpFrom = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
876
                let equalityOpTo = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
877

    
878
                if (selectedFromValue) {
879
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOpFrom + "\"" + selectedFromValue + "\"";
880
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
881
                }
882
                if (selectedToValue) {
883
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][1] + equalityOpTo + "\"" + selectedToValue + "\"";
884
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
885
                }
886
                if(selectedFromValue || selectedToValue) {
887
                  fq = "&fq=" + StringUtils.URIEncode(fq);
888
                }
889
              }
890
            }
891
          }
892
        }
893
        allFqs += fq +fqFrom + fqTo;
894
      }
895
    }
896

    
897
    return allFqs;
898

    
899
  }
900

    
901
  /**
902
   * Sets parameterNames and parameterValues arrays
903
   * used in paging, advanced search link, Goto()
904
   * @param filters either query filters or filters defined by the URL parameters
905
   * @param rangeFilters defined by the URL parameters
906
   * @param includePage
907
   */
908
  buildPageURLParameters(filters:Filter[], rangeFilters: RangeFilter[], includePage: boolean) {
909
    this.parameterNames.splice(0, this.parameterNames.length);
910
    this.parameterValues.splice(0, this.parameterValues.length);
911
    var fields: { [key: string]: { values: string[], operators: string[] } } = {};
912
    for (var i = 0; i < this.selectedFields.length; i++) {
913
      if (this.fieldIdsMap[this.selectedFields[i].id] != undefined && (this.selectedFields[i].value.length > 0 || this.selectedFields[i].type == "date")) {
914
        if (!fields[this.selectedFields[i].id]) {
915
          fields[this.selectedFields[i].id] = {values: [], operators: []};
916
          fields[this.selectedFields[i].id].values = [];
917
          fields[this.selectedFields[i].id].operators = [];
918
        }
919
        if (this.selectedFields[i].type == "date") {
920
          if (this.selectedFields[i].dateValue.type == "range") {
921
            fields[this.selectedFields[i].id].values.push(StringUtils.quote(StringUtils.URIEncode("range" + Dates.getDateToString(this.selectedFields[i].dateValue.from) + ":" + Dates.getDateToString(this.selectedFields[i].dateValue.to))));
922
          } else {
923
            fields[this.selectedFields[i].id].values.push(StringUtils.quote(StringUtils.URIEncode(this.selectedFields[i].dateValue.type)));
924
          }
925
        } else {
926
          fields[this.selectedFields[i].id].values.push(StringUtils.quote(StringUtils.URIEncode(this.selectedFields[i].value)));
927
        }
928
        fields[this.selectedFields[i].id].operators.push(this.selectedFields[i].operatorId);
929

    
930
      }
931
    }
932
    for (var i = 0; i < this.fieldIds.length; i++) {
933
      if (fields[this.fieldIds[i]]) {
934
        this.parameterNames.push(this.fieldIdsMap[this.fieldIds[i]].param);
935
        this.parameterValues.push(fields[this.fieldIds[i]].values.join());
936
        this.parameterNames.push(this.fieldIdsMap[this.fieldIds[i]].operator);
937
        this.parameterValues.push(fields[this.fieldIds[i]].operators.join());
938
      }
939
    }
940
    if (includePage && this.searchUtils.page != 1) {
941
      this.parameterNames.push("page");
942
      this.parameterValues.push("" + this.searchUtils.page);
943
    }
944

    
945
    if (this.searchUtils.size != this.resultsPerPage) {
946
      this.parameterNames.push("size");
947
      this.parameterValues.push("" + this.searchUtils.size);
948
    }
949

    
950
    if (this.sort && this.searchUtils.sortBy) {
951
      this.parameterNames.push("sortBy");
952
      this.parameterValues.push(this.searchUtils.sortBy);
953
    }
954
    for (let filter of filters) {
955
      var filterLimits = "";
956
      if (filter.countSelectedValues > 0) {
957
        for (let value of filter.values) {
958
          if (value.selected == true) {
959
            filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + (value.id) + '"';
960
          }
961
        }
962
        if (filterLimits.length > 0) {
963
          this.parameterNames.push(filter.filterId);
964
          this.parameterValues.push(filterLimits);
965
        }
966
      }
967
    }
968
    for (let filter of rangeFilters) {
969
      var filterLimits = "";
970
      let yearFrom: string = (Dates.isValidYear(filter.selectedFromValue) ? filter.selectedFromValue : null);
971
      let yearTo: string = (Dates.isValidYear(filter.selectedToValue) ? filter.selectedToValue : null);
972
      if(yearFrom || yearTo) {
973
        this.parameterNames.push(filter.filterId);
974
        this.parameterValues.push("range" + (yearFrom ? yearFrom : "") + ":" + (yearTo ? yearTo : ""));
975
      }
976
      // if (filter.countSelectedValues > 0) {
977
      //   for (let value of filter.values) {
978
      //     if (value.selected == true) {
979
      //       filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + (value.id) + '"';
980
      //     }
981
      //   }
982
      //   if (filterLimits.length > 0) {
983
      //     this.parameterNames.push(filter.filterId);
984
      //     this.parameterValues.push(filterLimits);
985
      //   }
986
      // }
987
    }
988
    if (this.searchUtils.keyword.length > 0) {
989
      this.parameterNames.push("keyword");
990
      this.parameterValues.push(this.searchUtils.keyword);
991
    }
992

    
993
    if (this.resultTypes && this.entityType == "result") {
994
      let values = [];
995
      if (this.resultTypes.publication) {
996
        values.push("publications");
997
      }
998
      if (this.resultTypes.dataset) {
999
        values.push("datasets");
1000
      }
1001
      if (this.resultTypes.software) {
1002
        values.push("software");
1003
      }
1004
      if (this.resultTypes.other) {
1005
        values.push("other");
1006
      }
1007
      if (values.length > 0) {
1008
        this.parameterNames.push("type");
1009
        this.parameterValues.push(values.join(","));
1010
      }
1011
      if(this.quickFilter) {
1012
        this.parameterNames.push("qf");
1013
        this.parameterValues.push("" + this.quickFilter.selected);
1014
      }
1015
    }
1016

    
1017
    // if (this.searchUtils.size != this.resultsPerPage) {
1018
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'size=' + this.searchUtils.size;
1019
    //   this.parameterNames.push("size");
1020
    //   this.parameterValues.push("" + this.searchUtils.size);
1021
    // }
1022
    // if (this.sort && this.searchUtils.sortBy) {
1023
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'sortBy=' + this.searchUtils.sortBy;
1024
    //   this.parameterNames.push("sortBy");
1025
    //   this.parameterValues.push(this.searchUtils.sortBy);
1026
    // }
1027
    // console.log(this.parameterNames)
1028
    // console.log(this.parameterValues)
1029
  }
1030

    
1031
  /**
1032
   * create filters based on URL params
1033
   * @param URLparams
1034
   */
1035
  getRefineFiltersFromURL(URLparams) {
1036
    let fields = new SearchFields();
1037
    let filters: Filter[] = [];
1038
    for (let i = 0; i < this.refineFields.length; i++) {
1039
      let filterId = this.refineFields[i];
1040
      if (URLparams[filterId] != undefined) {
1041
        let filter = new Filter();
1042
        filter.title = fields.getFieldName(filterId, this.entityType);
1043
        filter.filterId = filterId;
1044
        filter.originalFilterId = filterId;
1045
        filter.values = [];
1046
        let values = StringUtils.URIDecode(URLparams[filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1047
        for (let value of values) {
1048

    
1049
          let v: Value = new Value();
1050
          v.name = RefineResultsUtils.keepPartAfterCharacters(StringUtils.unquote(value), "||");
1051
          v.id = StringUtils.unquote(value);
1052
          v.selected = true;
1053
          filter.values.push(v);
1054
          // console.log(v)
1055
          filter.countSelectedValues++;
1056
        }
1057
        filters.push(filter)
1058
      }
1059
    }
1060

    
1061
    if (this.quickFilter) {
1062
      if (this.entityType == "result" && (URLparams[this.quickFilter.filterId] == undefined) && (URLparams["qf"] == undefined || URLparams["qf"] == "true")) {
1063
        let filter = new Filter();
1064
        filter.title = fields.getFieldName(this.quickFilter.filterId, this.entityType);
1065
        filter.filterId = this.quickFilter.filterId;
1066
        filter.originalFilterId = this.quickFilter.filterId;
1067
        filter.values = [];
1068
        let v: Value = new Value();
1069
        v.name = this.quickFilter.value;
1070
        v.id = this.quickFilter.value;
1071
        v.selected = true;
1072
        filter.values.push(v);
1073
        filter.countSelectedValues = 1;
1074
        filters.push(filter)
1075
      }
1076
    }
1077
    if (this.entityType == "result") {
1078
      this.resultTypes = null;
1079
      this.resultTypes = {
1080

    
1081
      };
1082

    
1083
      if (URLparams["type"]) {
1084

    
1085
        this.resultTypes['publication'] = (URLparams["type"].split(",").indexOf("publications") != -1);
1086
        this.resultTypes['dataset'] = (URLparams["type"].split(",").indexOf("datasets") != -1);
1087
        this.resultTypes['software'] = (URLparams["type"].split(",").indexOf("software") != -1);
1088
        this.resultTypes['other'] = (URLparams["type"].split(",").indexOf("other") != -1);
1089

    
1090
      } else {
1091
        this.resultTypes['publication'] = true;
1092
        this.resultTypes['dataset'] = true;
1093
        this.resultTypes['software'] = true;
1094
        this.resultTypes['other'] = true;
1095
      }
1096

    
1097
    }
1098

    
1099
    this.URLCreatedFilters = filters;
1100
  }
1101

    
1102
  /**
1103
   * create range filters based on URL params
1104
   * @param URLparams
1105
   */
1106
  getRangeFiltersFromURL(URLparams) {
1107
    let fields = new SearchFields();
1108
    let filters: RangeFilter[] = [];
1109
    for (let i = 0; i < this.rangeFields.length; i++) {
1110
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
1111
      let filterParam = fields.getFieldParam(filterId, this.entityType);
1112
      //console.log("rangeFilter (from url): filterId - filterParam");
1113
      //console.log(filterId + " - "+ filterParam);
1114
      if (URLparams[filterParam] != undefined) {
1115
        let filter = new RangeFilter();
1116
        filter.title = fields.getFieldName(filterId, this.entityType);
1117
        filter.filterId = filterParam;
1118
        filter.originalFilterIdFrom = this.rangeFields[i][0];
1119
        filter.originalFilterIdTo = this.rangeFields[i][1];
1120

    
1121

    
1122
        let values = (decodeURIComponent(URLparams[filterParam])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1123
        for (let j = 0; j < values.length; j++) {
1124
          if (this.fieldIdsMap[filterId].filterType == "range") {
1125
            let value: string = StringUtils.unquote(values[j]);
1126
            let validDates: boolean = true;
1127
            // if (value.length < 14) {
1128
            //   validDates = false;
1129
            // } else {
1130
            //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
1131
            //     validDates = false;
1132
            //   } else {
1133
            //     filter.selectedFromValue = value.substring(5, 9);
1134
            //     filter.selectedToValue = value.substring(10, 14);
1135
            //   }
1136
            // }
1137
            let years: string[] = (value.substring(5)).split(":");
1138
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
1139
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
1140
            //console.log("getRangeFiltersFromURL: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
1141
            if(yearFrom) {
1142
              filter.selectedFromValue = yearFrom;
1143
              //filter.selectedFromAndToValues = yearFrom;
1144
            }
1145
            /*if(yearFrom && yearTo) {
1146
              filter.selectedFromAndToValues += "-";
1147
            }*/
1148
            if(yearTo) {
1149
              filter.selectedToValue = yearTo;
1150
              //filter.selectedFromAndToValues += yearTo;
1151
            }
1152
            //console.log("filter.selectedFromAndToValues: "+filter.selectedFromAndToValues);
1153
            if(!yearFrom && !yearTo) {
1154
              validDates = false;
1155
            }
1156

    
1157
          }
1158
        }
1159
        //console.log(filters);
1160
        filters.push(filter)
1161
      }
1162
    }
1163
    // console.log("Empty Filters");
1164
    // console.log(filters);
1165
    this.URLCreatedRangeFilters = filters;
1166
    // return filters;
1167

    
1168
  }
1169

    
1170
  /**
1171
   * Checks if query has no results, display Filters from URL parameters
1172
   * Mark checked  the selected filters
1173
   * Count the checked
1174
   * @param filters
1175
   */
1176
  public prepareFiltersToShow(filters: Filter[]): Filter[] {
1177
    //console.log("prepareFiltersToShow");
1178
    if (this.URLCreatedFilters.length > 0 && this.searchUtils.totalResults == 0) {
1179
      this.showUnknownFilters = true;
1180
      this.filters = this.URLCreatedFilters;
1181
    } else if (this.searchUtils.totalResults != 0) {
1182
      this.showUnknownFilters = false;
1183
      this.filters = filters;
1184
    }
1185
    this.buildPageURLParameters(this.URLCreatedFilters, this.URLCreatedRangeFilters, true);
1186
    //this.checkSelectedRangeFilters(this.rangeFilters);
1187

    
1188
    this.checkSelectedFilters(this.filters);
1189
    this.countSelectedFilters(this.filters);
1190
    return this.filters;
1191
  }
1192

    
1193
  /**
1194
   * Mark checked  the selected range filters
1195
   */
1196
  public prepareRangeFiltersToShow() {
1197
    this.rangeFilters = RangeFilter.parse(this.rangeFields, this.entityType); // OK
1198

    
1199
    //this.buildPageURLRangeParameters(this.rangeFilters, true);
1200
    this.checkSelectedRangeFilters(this.rangeFilters);
1201
    this.countSelectedRangeFilters(this.rangeFilters);
1202
    return this.rangeFilters;
1203
  }
1204

    
1205
  /**
1206
   * Used to set the variables and search page, and prepare it before the getResults query
1207
   * @param fieldIds
1208
   * @param selectedFields
1209
   * @param refineFields
1210
   * @param fieldIdsMap
1211
   * @param customFilter
1212
   * @param params
1213
   */
1214
  prepareSearchPage(fieldIds, selectedFields, refineFields, rangeFields, fieldIdsMap, customFilter, params, entityType, quickFilter=null){
1215
    //console.log("prepareSearchPage");
1216
    this.entityType = entityType;
1217
    this.fieldIds = fieldIds;
1218
    this.selectedFields = selectedFields;
1219
    this.refineFields = refineFields;
1220
    this.rangeFields = rangeFields;
1221
    this.fieldIdsMap = fieldIdsMap;
1222
    this.customFilter = customFilter;
1223
    this.quickFilter = quickFilter;
1224
    this.getRangeFiltersFromURL(params);
1225
    this.getRefineFiltersFromURL(params);
1226
    this.createAdvancedSearchSelectedFiltersFromURLParameters(params);
1227
  }
1228
}
(20-20/54)