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

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

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

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

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

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

    
47
  eventTitleFormArray: any;
48
  eventAuthorFormArray: any;
49
  eventSubjectsFormArray: any;
50
  eventDateRangesFormArray: any;
51

    
52
  frequencyChoice: string;
53
  userEmail: string;
54
  modalErrorMessage: string;
55

    
56
  isModalShown: boolean;
57
  @ViewChild('subscribeToEventsModal')
58
  public subscribeToEventsModal: ConfirmationDialogComponent;
59

    
60
  constructor (private route: ActivatedRoute,
61
               private fb: FormBuilder,
62
               private brokerService: BrokerService,
63
               private authService: AuthenticationService) {}
64

    
65
  ngOnInit () {
66
    this.userEmail = this.authService.getUserEmail();
67
    this.getParams();
68
    this.initQuery();
69
    this.initForm();
70
    this.currentPage = 0; /* DELETE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
71
    this.getEventsPage(0);
72
  }
73

    
74
  getParams() {
75
    this.topic = this.route.snapshot.paramMap.get('topic');
76
    console.log(`my topic is: ${this.topic}`);
77
    this.lastTopicEntry = this.topic.substring(this.topic.lastIndexOf('|') + 1).toLowerCase();
78
    this.lastTopicEntry = this.replaceAll(this.lastTopicEntry, '_', ' ');
79
    this.getCorrectTopic();
80
    this.repoName = this.route.snapshot.paramMap.get('name');
81
  }
82

    
83
  replaceAll(str, find, replace) {
84
    return str.replace(new RegExp(find, 'g'), replace);
85
  }
86

    
87
  initQuery() {
88
    this.advanceSearch = {
89
      datasource: this.repoName,
90
      topic: this.correctTopic,
91
      titles: [],
92
      subjects: [],
93
      authors: [],
94
      dates: [],
95
      trust: {min: '0', max: '1'},
96
      page: 0
97
    };
98
  }
99

    
100
  initForm() {
101
    this.group = this.fb.group( this.groupDefinition, { validator: checkMinMax } );
102
    this.group.get('trustMin').setValue(0);
103
    this.group.get('trustMax').setValue(1);
104
  }
105

    
106
  initControl(definition: any) {
107
    return this.fb.group(definition);
108
  }
109

    
110
  removeControl(controlName: string, i: number) {
111
    const controlArray = <FormArray>this.group.controls[controlName];
112
    controlArray.removeAt(i);
113
  }
114

    
115
  addControl(controlName: string, definition: any) {
116
    const controlArray = <FormArray>this.group.controls[controlName];
117
    controlArray.push(this.initControl(definition));
118
  }
119

    
120
  clearForm() {
121
    let controlArray: FormArray;
122
    controlArray = <FormArray>this.group.controls['eventTitles'];
123
    controlArray.controls = [];
124
    controlArray.push(this.initControl(this.titleDefinition));
125

    
126
    controlArray = <FormArray>this.group.controls['eventAuthors'];
127
    controlArray.controls = [];
128
    controlArray.push(this.initControl(this.authorDefinition));
129

    
130
    controlArray = <FormArray>this.group.controls['eventSubjects'];
131
    controlArray.controls = [];
132
    controlArray.push(this.initControl(this.subjectDefinition));
133

    
134
    controlArray = <FormArray>this.group.controls['eventDateRanges'];
135
    controlArray.controls = [];
136
    controlArray.push(this.initControl(this.dateRangeDefinition));
137

    
138
    this.group.get('trustMin').setValue(0);
139
    this.group.get('trustMax').setValue(1);
140

    
141
    this.initQuery();
142
    this.getEventsPage(0);
143
  }
144

    
145
  updateQuery() {
146
    let i: number;
147
    let controlArray: FormArray;
148

    
149
    if ( this.group.valid ) {
150
      this.initQuery();
151
      this.advanceSearch.trust.min = this.group.get('trustMin').value;
152
      this.advanceSearch.trust.max = this.group.get('trustMax').value;
153

    
154
      controlArray = <FormArray>this.group.controls['eventTitles'];
155
      for (i = 0; i < controlArray.length; i++) {
156
        if (controlArray.at(i).get('eventTitle').value) {
157
          this.advanceSearch.titles.push(controlArray.at(i).get('eventTitle').value);
158
        }
159
      }
160
      controlArray = <FormArray>this.group.controls['eventAuthors'];
161
      for (i = 0; i < controlArray.length; i++) {
162
        if (controlArray.at(i).get('eventAuthor').value) {
163
          this.advanceSearch.authors.push(controlArray.at(i).get('eventAuthor').value);
164
        }
165
      }
166
      controlArray = <FormArray>this.group.controls['eventSubjects'];
167
      for (i = 0; i < controlArray.length; i++) {
168
        if (controlArray.at(i).get('eventSubject').value) {
169
          this.advanceSearch.subjects.push(controlArray.at(i).get('eventSubject').value);
170
        }
171
      }
172
      controlArray = <FormArray>this.group.controls['eventDateRanges'];
173
      for (i = 0; i < controlArray.length; i++) {
174
        if (controlArray.at(i).get('dateFrom').value) {
175
          let toDate;
176
          if (controlArray.at(i).get('dateTo').value ||
177
              (controlArray.at(i).get('dateFrom').value > controlArray.at(i).get('dateTo').value) ) {
178
            toDate = controlArray.at(i).get('dateTo').value;
179
          } else {
180
            toDate = Date.now();
181
          }
182
          this.advanceSearch.dates.push({
183
            min: controlArray.at(i).get('dateFrom').value,
184
            max: toDate
185
          });
186
        }
187
      }
188
      console.log(this.advanceSearch);
189
      this.currentPage = 0; /* DELETE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
190
      this.getEventsPage(0);
191
    }
192
  }
193

    
194
  getEventsPage(page: number) {
195
    this.noEvents = '';
196
    this.errorMessage = '';
197
    this.successMessage = '';
198
    this. loadingMessage = loadingEvents;
199
    this.brokerService.advancedShowEvents(page, 10, this.advanceSearch).subscribe(
200
      events => this.eventsPage = events,
201
      error => {
202
        this.loadingMessage = '';
203
        this.errorMessage = noServiceMessage;
204
        console.log(error);
205
      },
206
      () => {
207
        this.loadingMessage = '';
208
        console.log(this.eventsPage);
209
        if (!this.eventsPage.total) {
210
          if (!this.eventsPageInitialized) {
211
            this.noEvents = noEventsForTopic;
212
          } else {
213
            this.noEvents = noEventsWithParams;
214
          }
215
        }
216
        let tempArray = <FormArray>this.group.controls['eventTitles'];
217
        this.eventTitleFormArray = tempArray.controls;
218
        tempArray = <FormArray>this.group.controls['eventAuthors'];
219
        this.eventAuthorFormArray = tempArray.controls;
220
        tempArray = <FormArray>this.group.controls['eventSubjects'];
221
        this.eventSubjectsFormArray = tempArray.controls;
222
        tempArray = <FormArray>this.group.controls['eventDateRanges'];
223
        this.eventDateRangesFormArray = tempArray.controls;
224
        console.log(`total pages is ${this.eventsPage.totalPages}`);
225
        this.eventsPageInitialized = true;
226
      }
227
    );
228
  }
229

    
230
  isHighlighted(item: any, itemList: any[]) {
231
    return itemList.some(x => x === item);
232
  }
233

    
234
  getCorrectTopic() {
235
    const temp = this.topic.split('|');
236
    this.correctTopic = temp[0];
237
    this.topic = temp[0];
238
    for (let i = 1; i < temp.length; i++) {
239
      this.correctTopic += `/${temp[i]}`;
240
      this.topic += ` | ${temp[i]}`;
241
    }
242
  }
243

    
244
  goToNextPage() {
245
    /* RESTORE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
246
    /*if(this.eventsPage.currPage < this.eventsPage.totalPages) {
247
      console.log(`Get me page ${this.eventsPage.currPage+1}!`);
248
      this.getEventsPage(this.eventsPage.currPage+1);
249
    }*/
250

    
251
    /* DELETE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
252
    if ( (this.currentPage + 1) < this.eventsPage.totalPages) {
253
      this.currentPage = this.currentPage + 1;
254
      console.log(`Get me page ${this.currentPage}!`);
255
      this.getEventsPage(this.currentPage);
256
    }
257

    
258
  }
259

    
260
  goToPreviousPage() {
261
    /* RESTORE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
262
    /*if(this.eventsPage.currPage > 0) {
263
      console.log(`Get me page ${this.eventsPage.currPage-1}!`);
264
      this.getEventsPage(this.eventsPage.currPage-1);
265
    }*/
266

    
267
    /* DELETE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
268
    if (this.currentPage > 0) {
269
      this.currentPage = this.currentPage - 1;
270
      console.log(`Get me page ${this.currentPage}!`);
271
      this.getEventsPage(this.currentPage);
272
    }
273
  }
274

    
275
  showSubscriptionModal() {
276
    if (this.advanceSearch && this.eventsPage) {
277
      this.subscribeToEventsModal.confirmed = false;
278
      this.subscribeToEventsModal.showModal();
279
    }
280
  }
281

    
282
  choseFrequency(freq: string) {
283
    this.frequencyChoice = freq;
284
  }
285

    
286
  subscribeToEvents(event: any) {
287
    this.modalErrorMessage = '';
288
    if (this.frequencyChoice) {
289
      this.subscribeToEventsModal.confirmed = true;
290
      const freq = <NotificationFrequency>this.frequencyChoice;
291
      const mod: NotificationMode = 'EMAIL';
292
      const sub = {
293
        subscriber: this.userEmail,
294
        frequency: freq,
295
        mode: mod,
296
        query: this.advanceSearch
297
      };
298
      this.errorMessage = '';
299
      this.successMessage = '';
300
      console.log(JSON.stringify(sub));
301
      this.loadingMessage = subscribingToEvents;
302
      this.brokerService.subscribeToEvent(sub).subscribe(
303
        response => console.log(`subscribeToEvents responded ${JSON.stringify(response)}`),
304
        error => {
305
          this.errorMessage = subscribingToEventsError;
306
          this.loadingMessage = '';
307
        },
308
        () => {
309
          this.loadingMessage = '';
310
          this.successMessage = subscribingToeventsSuccess;
311
        }
312
      );
313
    } else {
314
      this.modalErrorMessage = subscribingChooseFrequency;
315
    }
316
  }
317

    
318
}
319

    
320
export function checkMinMax(c: AbstractControl) {
321
  if ( c.get('trustMin').value > c.get('trustMax').value ) {
322
    return 'invalid';
323
  }
324
  return null;
325
}
326

    
327
export function checkDates(c: AbstractControl) {
328
  if ( c.get('dateFrom').value > c.get('dateTo').value ) {
329
    return 'invalid';
330
  }
331
  return null;
332
}
(2-2/13)