Project

General

Profile

1
import { Component, OnInit, ViewChild } from '@angular/core';
2
import { ActivatedRoute } from '@angular/router';
3
import { AdvQueryObject, EventsPage, NotificationFrequency, NotificationMode } from '../../../domain/typeScriptClasses';
4
import { BrokerService } from '../../../services/broker.service';
5
import { loadingEvents, noEventsForTopic, noEventsWithParams, noServiceMessage,
6
         subscribingChooseFrequency, subscribingToEvents, subscribingToEventsError,
7
         subscribingToeventsSuccess } from '../../../domain/shared-messages';
8
import { AbstractControl, FormArray, FormBuilder, FormGroup } from '@angular/forms';
9
import { AuthenticationService } from '../../../services/authentication.service';
10
import { ConfirmationDialogComponent } from '../../../shared/reusablecomponents/confirmation-dialog.component';
11
import { SharedService } from "../../../services/shared.service";
12

    
13
@Component ({
14
  selector: 'app-content-events-of-repo-eventslist',
15
  templateUrl: 'content-events-of-repo-eventslist.component.html'
16
})
17

    
18
export class ContentEventsOfRepoEventslistComponent implements OnInit {
19
  errorMessage: string;
20
  loadingMessage: string;
21
  successMessage: string;
22
  noEvents: string;
23
  eventsPageInitialized = false;
24

    
25
  topic = '';
26
  lastTopicEntry = '';
27
  correctTopic = '';
28
  repoName = '';
29

    
30
  advanceSearch: AdvQueryObject;
31
  eventsPage: EventsPage;
32
  currentPage: number; /* DELETE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
33

    
34
  selectedItemIndex: number;
35

    
36
  group: FormGroup;
37
  readonly titleDefinition = { eventTitle: [''] };
38
  readonly authorDefinition = { eventAuthor: [''] };
39
  readonly subjectDefinition = { eventSubject: [''] };
40
  readonly dateRangeDefinition = { dateFrom: '', dateTo: '' };
41
  readonly groupDefinition = {
42
    trustMin: [+''],
43
    trustMax: [+''],
44
    eventTitles: this.fb.array([this.initControl(this.titleDefinition)]),
45
    eventAuthors: this.fb.array([this.initControl(this.authorDefinition)]),
46
    eventSubjects: this.fb.array([this.initControl(this.subjectDefinition)]),
47
    eventDateRanges: this.fb.array([this.initControl(this.dateRangeDefinition)])
48
  };
49

    
50
  eventTitleFormArray: any;
51
  eventAuthorFormArray: any;
52
  eventSubjectsFormArray: any;
53
  eventDateRangesFormArray: any;
54

    
55
  frequencyChoice = 'daily';
56
  userEmail: string;
57
  modalErrorMessage: string;
58

    
59
  isModalShown: boolean;
60
  @ViewChild('subscribeToEventsModal', { static: true })
61
  public subscribeToEventsModal: ConfirmationDialogComponent;
62

    
63
  constructor (private route: ActivatedRoute,
64
               private fb: FormBuilder,
65
               private brokerService: BrokerService,
66
               private authService: AuthenticationService,
67
               private sharedService: SharedService) {}
68

    
69
  ngOnInit () {
70

    
71
    this.userEmail = this.authService.getUserEmail();
72

    
73
    this.getParams();
74

    
75

    
76
    if(this.sharedService.getRepository()) {
77
      this.repoName = this.sharedService.getRepository().officialname;
78
      this.initQuery();
79
      this.initForm();
80
      this.currentPage = 0; /* DELETE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
81
      this.getEventsPage(0);
82
    }
83

    
84
    this.sharedService.repository$.subscribe(
85
      r => {
86
        if (r) {
87
          this.repoName = r.officialname;
88
          this.initQuery();
89
          this.initForm();
90
          this.currentPage = 0; /* DELETE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
91
          this.getEventsPage(0);
92
        }
93
      }
94
    );
95

    
96
    let body = document.getElementsByTagName('body')[0];
97
    body.classList.remove("top_bar_active");   //remove the class
98
    body.classList.add("page_heading_active");
99
    body.classList.remove("landing");
100
    body.classList.add("dashboard");
101
  }
102

    
103
  getParams() {
104
    this.topic = this.route.snapshot.paramMap.get('topic');
105
    console.log(`my topic is: ${this.topic}`);
106
    this.lastTopicEntry = this.topic.substring(this.topic.lastIndexOf('|') + 1).toLowerCase();
107
    this.lastTopicEntry = this.replaceAll(this.lastTopicEntry, '_', ' ');
108
    this.getCorrectTopic();
109
    // this.repoName = this.route.snapshot.paramMap.get('name');
110
  }
111

    
112
  replaceAll(str, find, replace) {
113
    return str.replace(new RegExp(find, 'g'), replace);
114
  }
115

    
116
  initQuery() {
117
    this.advanceSearch = {
118
      datasource: this.repoName,
119
      topic: this.correctTopic,
120
      titles: [],
121
      subjects: [],
122
      authors: [],
123
      dates: [],
124
      trust: {min: '0', max: '1'},
125
      page: 0
126
    };
127
  }
128

    
129
  initForm() {
130
    this.group = this.fb.group( this.groupDefinition, { validator: checkMinMax } );
131
    this.group.get('trustMin').setValue(0);
132
    this.group.get('trustMax').setValue(1);
133
  }
134

    
135
  initControl(definition: any) {
136
    return this.fb.group(definition);
137
  }
138

    
139
  removeControl(controlName: string, i: number) {
140
    const controlArray = <FormArray>this.group.controls[controlName];
141
    controlArray.removeAt(i);
142
  }
143

    
144
  addControl(controlName: string, definition: any) {
145
    const controlArray = <FormArray>this.group.controls[controlName];
146
    controlArray.push(this.initControl(definition));
147
  }
148

    
149
  clearForm() {
150
    let controlArray: FormArray;
151
    controlArray = <FormArray>this.group.controls['eventTitles'];
152
    controlArray.controls = [];
153
    controlArray.push(this.initControl(this.titleDefinition));
154

    
155
    controlArray = <FormArray>this.group.controls['eventAuthors'];
156
    controlArray.controls = [];
157
    controlArray.push(this.initControl(this.authorDefinition));
158

    
159
    controlArray = <FormArray>this.group.controls['eventSubjects'];
160
    controlArray.controls = [];
161
    controlArray.push(this.initControl(this.subjectDefinition));
162

    
163
    controlArray = <FormArray>this.group.controls['eventDateRanges'];
164
    controlArray.controls = [];
165
    controlArray.push(this.initControl(this.dateRangeDefinition));
166

    
167
    this.group.get('trustMin').setValue(0);
168
    this.group.get('trustMax').setValue(1);
169

    
170
    this.initQuery();
171
    this.getEventsPage(0);
172
  }
173

    
174
  updateQuery() {
175
    let i: number;
176
    let controlArray: FormArray;
177

    
178
    if ( this.group.valid ) {
179
      this.initQuery();
180
      this.advanceSearch.trust.min = this.group.get('trustMin').value;
181
      this.advanceSearch.trust.max = this.group.get('trustMax').value;
182

    
183
      controlArray = <FormArray>this.group.controls['eventTitles'];
184
      for (i = 0; i < controlArray.length; i++) {
185
        if (controlArray.at(i).get('eventTitle').value) {
186
          this.advanceSearch.titles.push(controlArray.at(i).get('eventTitle').value);
187
        }
188
      }
189
      controlArray = <FormArray>this.group.controls['eventAuthors'];
190
      for (i = 0; i < controlArray.length; i++) {
191
        if (controlArray.at(i).get('eventAuthor').value) {
192
          this.advanceSearch.authors.push(controlArray.at(i).get('eventAuthor').value);
193
        }
194
      }
195
      controlArray = <FormArray>this.group.controls['eventSubjects'];
196
      for (i = 0; i < controlArray.length; i++) {
197
        if (controlArray.at(i).get('eventSubject').value) {
198
          this.advanceSearch.subjects.push(controlArray.at(i).get('eventSubject').value);
199
        }
200
      }
201
      controlArray = <FormArray>this.group.controls['eventDateRanges'];
202
      for (i = 0; i < controlArray.length; i++) {
203
        if (controlArray.at(i).get('dateFrom').value) {
204
          let toDate;
205
          if (controlArray.at(i).get('dateTo').value ||
206
              (controlArray.at(i).get('dateFrom').value > controlArray.at(i).get('dateTo').value) ) {
207
            toDate = controlArray.at(i).get('dateTo').value;
208
          } else {
209
            toDate = Date.now();
210
          }
211
          this.advanceSearch.dates.push({
212
            min: controlArray.at(i).get('dateFrom').value,
213
            max: toDate
214
          });
215
        }
216
      }
217
      console.log(this.advanceSearch);
218
      this.currentPage = 0; /* DELETE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
219
      this.getEventsPage(0);
220
    }
221
  }
222

    
223
  getEventsPage(page: number) {
224
    this.noEvents = '';
225
    this.errorMessage = '';
226
    this.successMessage = '';
227
    this.loadingMessage = loadingEvents;
228
    this.brokerService.advancedShowEvents(page, 10, this.advanceSearch).subscribe(
229
      events => this.eventsPage = events,
230
      error => {
231
        this.loadingMessage = '';
232
        this.errorMessage = noServiceMessage;
233
        console.log(error);
234
      },
235
      () => {
236
        this.loadingMessage = '';
237
        console.log(this.eventsPage);
238
        if (!this.eventsPage.total) {
239
          if (!this.eventsPageInitialized) {
240
            this.noEvents = noEventsForTopic;
241
          } else {
242
            this.noEvents = noEventsWithParams;
243
          }
244
        }
245
        let tempArray = <FormArray>this.group.controls['eventTitles'];
246
        this.eventTitleFormArray = tempArray.controls;
247
        tempArray = <FormArray>this.group.controls['eventAuthors'];
248
        this.eventAuthorFormArray = tempArray.controls;
249
        tempArray = <FormArray>this.group.controls['eventSubjects'];
250
        this.eventSubjectsFormArray = tempArray.controls;
251
        tempArray = <FormArray>this.group.controls['eventDateRanges'];
252
        this.eventDateRangesFormArray = tempArray.controls;
253
        console.log(`total pages is ${this.eventsPage.totalPages}`);
254
        this.eventsPageInitialized = true;
255
      }
256
    );
257
  }
258

    
259
  isHighlighted(item: any, itemList: any[]) {
260
    return itemList.some(x => x === item);
261
  }
262

    
263
  getCorrectTopic() {
264
    const temp = this.topic.split('|');
265
    this.correctTopic = temp[0];
266
    this.topic = temp[0];
267
    for (let i = 1; i < temp.length; i++) {
268
      this.correctTopic += `/${temp[i]}`;
269
      this.topic += ` | ${temp[i]}`;
270
    }
271
  }
272

    
273
  goToNextPage() {
274
    /* RESTORE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
275
    /*if(this.eventsPage.currPage < this.eventsPage.totalPages) {
276
      console.log(`Get me page ${this.eventsPage.currPage+1}!`);
277
      this.getEventsPage(this.eventsPage.currPage+1);
278
    }*/
279

    
280
    /* DELETE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
281
    if ( (this.currentPage + 1) < this.eventsPage.totalPages) {
282
      this.currentPage = this.currentPage + 1;
283
      console.log(`Get me page ${this.currentPage}!`);
284
      this.getEventsPage(this.currentPage);
285

    
286
      window.scrollTo(0, 0);
287
    }
288

    
289
  }
290

    
291
  goToPreviousPage() {
292
    /* RESTORE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
293
    /*if(this.eventsPage.currPage > 0) {
294
      console.log(`Get me page ${this.eventsPage.currPage-1}!`);
295
      this.getEventsPage(this.eventsPage.currPage-1);
296
    }*/
297

    
298
    /* DELETE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
299
    if (this.currentPage > 0) {
300
      this.currentPage = this.currentPage - 1;
301
      console.log(`Get me page ${this.currentPage}!`);
302
      this.getEventsPage(this.currentPage);
303

    
304
      window.scrollTo(0, 0);
305
    }
306
  }
307

    
308
  showSubscriptionModal() {
309
    if (this.advanceSearch && this.eventsPage) {
310
      this.subscribeToEventsModal.confirmed = false;
311
      this.subscribeToEventsModal.showModal();
312
    }
313
  }
314

    
315
  choseFrequency(freq: string) {
316
    this.frequencyChoice = freq;
317
  }
318

    
319
  subscribeToEvents(event: any) {
320
    this.modalErrorMessage = '';
321
    if (this.frequencyChoice) {
322
      this.subscribeToEventsModal.confirmed = true;
323
      const freq = <NotificationFrequency>this.frequencyChoice;
324
      const mod: NotificationMode = 'EMAIL';
325
      const sub = {
326
        subscriber: this.userEmail,
327
        frequency: freq,
328
        mode: mod,
329
        query: this.advanceSearch
330
      };
331
      this.errorMessage = '';
332
      this.successMessage = '';
333
      console.log(JSON.stringify(sub));
334
      this.loadingMessage = subscribingToEvents;
335
      this.brokerService.subscribeToEvent(sub).subscribe(
336
        response => console.log(`subscribeToEvents responded ${JSON.stringify(response)}`),
337
        error => {
338
          this.errorMessage = subscribingToEventsError;
339
          this.loadingMessage = '';
340
        },
341
        () => {
342
          this.loadingMessage = '';
343
          this.successMessage = subscribingToeventsSuccess;
344
        }
345
      );
346
    } else {
347
      this.modalErrorMessage = subscribingChooseFrequency;
348
    }
349
  }
350

    
351
  // displayFullResultInfo(i: number) {
352
  //   if (this.selectedItemIndex === i) {
353
  //     this.selectedItemIndex = null;
354
  //   } else {
355
  //     this.selectedItemIndex = i;
356
  //   }
357
  // }
358

    
359
  showMore(i: number) {
360
    this.selectedItemIndex = i;
361
  }
362

    
363
  showLess(i: number) {
364
    this.selectedItemIndex = null;
365
  }
366

    
367
}
368

    
369
export function checkMinMax(c: AbstractControl) {
370
  if ( c.get('trustMin').value > c.get('trustMax').value ) {
371
    return 'invalid';
372
  }
373
  return null;
374
}
375

    
376
export function checkDates(c: AbstractControl) {
377
  if ( c.get('dateFrom').value > c.get('dateTo').value ) {
378
    return 'invalid';
379
  }
380
  return null;
381
}
(2-2/6)