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 {
6
  loadingEvents, noEventsForTopic, noEventsWithParams, noServiceMessage, subscribingChooseFrequency,
7
  subscribingToEvents,
8
  subscribingToEventsError, subscribingToeventsSuccess
9
} from '../../domain/shared-messages';
10
import { AbstractControl, FormArray, FormBuilder, FormGroup, Validator, Validators } from '@angular/forms';
11
import { AuthenticationService } from '../../services/authentication.service';
12
import { ConfirmationDialogComponent } from '../../shared/reusablecomponents/confirmation-dialog.component';
13

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

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

    
26
  topic = '';
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
  group: FormGroup;
35
  readonly titleDefinition = { eventTitle: [''] };
36
  readonly authorDefinition = { eventAuthor: [''] };
37
  readonly subjectDefinition = { eventSubject: [''] };
38
  readonly dateRangeDefinition = { dateFrom: '', dateTo: '' };
39
  readonly groupDefinition = {
40
    trustMin: [+''],
41
    trustMax: [+''],
42
    eventTitles: this.fb.array([this.initControl(this.titleDefinition)]),
43
    eventAuthors: this.fb.array([this.initControl(this.authorDefinition)]),
44
    eventSubjects: this.fb.array([this.initControl(this.subjectDefinition)]),
45
    eventDateRanges: this.fb.array([this.initControl(this.dateRangeDefinition)])
46
  };
47

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
133
    this.group.get('trustMin').setValue(0);
134
    this.group.get('trustMax').setValue(1);
135

    
136
    this.initQuery();
137
    this.getEventsPage(0);
138
  }
139

    
140
  updateQuery() {
141
    let i: number;
142
    let controlArray: FormArray;
143

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

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

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

    
217
  getCorrectTopic() {
218
    let temp = this.topic.split('|');
219
    this.correctTopic = temp[0];
220
    this.topic = temp[0];
221
    for (let i=1; i<temp.length; i++){
222
      this.correctTopic += `/${temp[i]}`;
223
      this.topic += ` | ${temp[i]}`;
224
    }
225
  }
226

    
227
  goToNextPage(){
228
    /* RESTORE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
229
    /*if(this.eventsPage.currPage < this.eventsPage.totalPages) {
230
      console.log(`Get me page ${this.eventsPage.currPage+1}!`);
231
      this.getEventsPage(this.eventsPage.currPage+1);
232
    }*/
233

    
234
    /* DELETE WHEN ADVANCED SHOW EVENTS IS FIXED AND SENDS CORRECT VALUE FOR CURRENT PAGE */
235
    if( (this.currentPage+1) < this.eventsPage.totalPages) {
236
      this.currentPage = this.currentPage+1;
237
      console.log(`Get me page ${this.currentPage}!`);
238
      this.getEventsPage(this.currentPage);
239
    }
240

    
241
  }
242

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

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

    
258
  showSubscriptionModal() {
259
    if (this.advanceSearch && this.eventsPage) {
260
      this.subscribeToEventsModal.confirmed = false;
261
      this.subscribeToEventsModal.showModal();
262
    }
263
  }
264

    
265
  choseFrequency(freq: string) {
266
    this.frequencyChoice = freq;
267
  }
268

    
269
  subscribeToEvents(events: any) {
270
    this.modalErrorMessage = '';
271
    if (this.frequencyChoice) {
272
      this.subscribeToEventsModal.confirmed = true;
273
      let freq = <NotificationFrequency>this.frequencyChoice;
274
      let mod: NotificationMode = "EMAIL";
275
      let sub = {
276
        subscriber: this.userEmail,
277
        frequency: freq,
278
        mode: mod,
279
        query: this.advanceSearch
280
      };
281
      this.errorMessage = '';
282
      this.successMessage = '';
283
      console.log(JSON.stringify(sub));
284
      this.loadingMessage = subscribingToEvents;
285
      this.brokerService.subscribeToEvent(sub).subscribe(
286
        response => console.log(`subscribeToEvents responded ${response}`),
287
        error => {
288
          this.errorMessage = subscribingToEventsError;
289
          this.loadingMessage = '';
290
        },
291
        () => {
292
          this.loadingMessage = '';
293
          this.successMessage = subscribingToeventsSuccess;
294
        }
295
      );
296
    } else {
297
      this.modalErrorMessage = subscribingChooseFrequency;
298
    }
299
  }
300

    
301
}
302

    
303
export function checkMinMax(c: AbstractControl) {
304
  if( c.get('trustMin').value > c.get('trustMax').value ){
305
    return 'invalid';
306
  }
307
  return null;
308
}
309

    
310
export function checkDates(c: AbstractControl) {
311
  if( c.get('dateFrom').value > c.get('dateTo').value ) {
312
    return 'invalid';
313
  }
314
  return null;
315
}
(2-2/13)