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
  correctTopic = '';
26
  repoName = '';
27

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

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

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

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

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

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

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

    
73
  getParams() {
74
    this.topic = this.route.snapshot.paramMap.get('topic');
75
    console.log(`my topic is: ${this.topic}`);
76
    this.getCorrectTopic();
77
    this.repoName = this.route.snapshot.paramMap.get('name');
78
  }
79

    
80
  initQuery() {
81
    this.advanceSearch = {
82
      datasource: this.repoName,
83
      topic: this.correctTopic,
84
      titles: [],
85
      subjects: [],
86
      authors: [],
87
      dates: [],
88
      trust: {min: '0', max: '1'},
89
      page: 0
90
    };
91
  }
92

    
93
  initForm() {
94
    this.group = this.fb.group( this.groupDefinition, { validator: checkMinMax } );
95
    this.group.get('trustMin').setValue(0);
96
    this.group.get('trustMax').setValue(1);
97
  }
98

    
99
  initControl(definition: any) {
100
    return this.fb.group(definition);
101
  }
102

    
103
  removeControl(controlName: string, i: number) {
104
    const controlArray = <FormArray>this.group.controls[controlName];
105
    controlArray.removeAt(i);
106
  }
107

    
108
  addControl(controlName: string, definition: any) {
109
    const controlArray = <FormArray>this.group.controls[controlName];
110
    controlArray.push(this.initControl(definition));
111
  }
112

    
113
  clearForm() {
114
    let controlArray: FormArray;
115
    controlArray = <FormArray>this.group.controls['eventTitles'];
116
    controlArray.controls = [];
117
    controlArray.push(this.initControl(this.titleDefinition));
118

    
119
    controlArray = <FormArray>this.group.controls['eventAuthors'];
120
    controlArray.controls = [];
121
    controlArray.push(this.initControl(this.authorDefinition));
122

    
123
    controlArray = <FormArray>this.group.controls['eventSubjects'];
124
    controlArray.controls = [];
125
    controlArray.push(this.initControl(this.subjectDefinition));
126

    
127
    controlArray = <FormArray>this.group.controls['eventDateRanges'];
128
    controlArray.controls = [];
129
    controlArray.push(this.initControl(this.dateRangeDefinition));
130

    
131
    this.group.get('trustMin').setValue(0);
132
    this.group.get('trustMax').setValue(1);
133

    
134
    this.initQuery();
135
    this.getEventsPage(0);
136
  }
137

    
138
  updateQuery() {
139
    let i: number;
140
    let controlArray: FormArray;
141

    
142
    if ( this.group.valid ) {
143
      this.initQuery();
144
      this.advanceSearch.trust.min = this.group.get('trustMin').value;
145
      this.advanceSearch.trust.max = this.group.get('trustMax').value;
146

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

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

    
223
  isHighlighted(item: any, itemList: any[]) {
224
    return itemList.some(x => x === item);
225
  }
226

    
227
  getCorrectTopic() {
228
    const temp = this.topic.split('|');
229
    this.correctTopic = temp[0];
230
    this.topic = temp[0];
231
    for (let i = 1; i < temp.length; i++) {
232
      this.correctTopic += `/${temp[i]}`;
233
      this.topic += ` | ${temp[i]}`;
234
    }
235
  }
236

    
237
  goToNextPage() {
238
    /* RESTORE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
239
    /*if(this.eventsPage.currPage < this.eventsPage.totalPages) {
240
      console.log(`Get me page ${this.eventsPage.currPage+1}!`);
241
      this.getEventsPage(this.eventsPage.currPage+1);
242
    }*/
243

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

    
251
  }
252

    
253
  goToPreviousPage() {
254
    /* RESTORE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
255
    /*if(this.eventsPage.currPage > 0) {
256
      console.log(`Get me page ${this.eventsPage.currPage-1}!`);
257
      this.getEventsPage(this.eventsPage.currPage-1);
258
    }*/
259

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

    
268
  showSubscriptionModal() {
269
    if (this.advanceSearch && this.eventsPage) {
270
      this.subscribeToEventsModal.confirmed = false;
271
      this.subscribeToEventsModal.showModal();
272
    }
273
  }
274

    
275
  choseFrequency(freq: string) {
276
    this.frequencyChoice = freq;
277
  }
278

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

    
311
}
312

    
313
export function checkMinMax(c: AbstractControl) {
314
  if ( c.get('trustMin').value > c.get('trustMax').value ) {
315
    return 'invalid';
316
  }
317
  return null;
318
}
319

    
320
export function checkDates(c: AbstractControl) {
321
  if ( c.get('dateFrom').value > c.get('dateTo').value ) {
322
    return 'invalid';
323
  }
324
  return null;
325
}
(2-2/13)