Project

General

Profile

1
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
2
import {FormArray, FormBuilder, FormControl} from '@angular/forms';
3
import {ActivatedRoute, Router} from '@angular/router';
4
import {HelpContentService} from '../../../services/help-content.service';
5
import {CommunityService} from '../../../openaireLibrary/connect/community/community.service';
6
import {SubjectsService} from '../subjects.service';
7
import {EnvProperties} from '../../../openaireLibrary/utils/properties/env-properties';
8
import {Session} from '../../../openaireLibrary/login/utils/helper.class';
9
import {LoginErrorCodes} from '../../../openaireLibrary/login/utils/guardHelper.class';
10

    
11
import {concat} from 'rxjs/observable/concat';
12
import {HelperFunctions} from '../../../openaireLibrary/utils/HelperFunctions.class';
13
import {Title} from '@angular/platform-browser';
14
import {properties} from '../../../../environments/environment';
15
import {AlertModal} from '../../../openaireLibrary/utils/modal/alert';
16
import {SearchInputComponent} from '../../../openaireLibrary/sharedComponents/search-input/search-input.component';
17
import {Subscription} from 'rxjs';
18
import {CommunityInfo} from '../../../openaireLibrary/connect/community/communityInfo';
19

    
20
declare var UIkit;
21

    
22
@Component({
23
  selector: 'subjects-edit-form',
24
  templateUrl: './subjects-edit-form.component.html',
25
})
26

    
27
export class SubjectsEditFormComponent implements OnInit {
28
  myForm = new FormArray([new FormControl({subject: ''})]);
29
  public showLoading = true;
30
  public res = [];
31
  params: any;
32
  public communityId: string = null;
33
  public community: CommunityInfo = null;
34
  public properties: EnvProperties = properties;
35
  public edit = null;
36
  public originalSubjects = [];
37
  @ViewChild('editModal') editModal: AlertModal;
38
  @ViewChild('deleteModal') deleteModal: AlertModal;
39
  page = 1;
40
  size = 10;
41
  selectedSubjects = [];
42
  isEditModal: boolean = false;
43
  public selectedKeyword: string;
44
  @ViewChild('searchInputComponent') searchInputComponent: SearchInputComponent;
45
  public filterForm: FormControl;
46
  private subscriptions: any[] = [];
47
  
48
  constructor(private element: ElementRef,
49
              private route: ActivatedRoute,
50
              private _router: Router,
51
              public _fb: FormBuilder,
52
              private title: Title,
53
              private _helpContentService: HelpContentService,
54
              private _communityService: CommunityService,
55
              private _subjectsService: SubjectsService,
56
  ) {
57
  }
58
  
59
  
60
  ngOnInit() {
61
    this.filterForm = this._fb.control('');
62
    this.subscriptions.push(this.filterForm.valueChanges.subscribe(value => {
63
      this.page = 1;
64
      this.community.subjects = this.originalSubjects.filter(subject => {
65
        return subject.toLowerCase().indexOf(value.toLowerCase()) != -1
66
      });
67
    }));
68
    this.subscriptions.push(this.route.params.subscribe(
69
      params => {
70
        this.communityId = params['community'];
71
        this.title.setTitle(this.communityId.toUpperCase() + ' | Subjects');
72
        this.showLoading = true;
73
        this.subscriptions.push(this._communityService.getCommunityAsObservable().subscribe(
74
          community => {
75
            this.community = community;
76
            this.params = {
77
              community: encodeURIComponent(
78
                '"' + community.queryId + '"')
79
            };
80
            this.originalSubjects = [];
81
            for (let i = 0; i < this.community.subjects.length; i++) {
82
              this.originalSubjects.push(this.community.subjects[i]);
83
            }
84
            if (this.community.subjects.length === 0) {
85
              this.community.subjects.push('');
86
            }
87
            this.showLoading = false;
88
          },
89
          error => this.handleUpdateError('System error retrieving community profile', error)
90
        ));
91
      }));
92
    
93
  }
94
  
95
  ngOnDestroy() {
96
    this.subscriptions.forEach(subscription => {
97
      if (subscription instanceof Subscription) {
98
        subscription.unsubscribe();
99
      }
100
    });
101
  }
102
  
103
  private removeModalOpen(subject: string, i: any) {
104
    if (!Session.isLoggedIn()) {
105
      this._router.navigate(['/user-info'], {
106
        queryParams: {
107
          "errorCode": LoginErrorCodes.NOT_VALID,
108
          "redirectUrl": this._router.url
109
        }
110
      });
111
    } else {
112
      this.selectedSubjects = [subject];
113
      this.reset(['']);
114
      this.deleteModal.cancelButton = true;
115
      this.deleteModal.okButton = true;
116
      this.deleteModal.alertTitle = 'Delete Confirmation';
117
      this.deleteModal.message = 'Are you sure you want to delete this subject?';
118
      this.deleteModal.okButtonText = 'Yes';
119
      this.deleteModal.cancelButtonText = 'No';
120
      this.deleteModal.open();
121
    }
122
  }
123
  
124
  
125
  public getSubjectsExistOnlyInFirst(firstArray: string[], secondArray: string[]): string[] {
126
    const difference = [];
127
    for (let i = 0; i < firstArray.length; i++) {
128
      if (secondArray.indexOf(firstArray[i]) === -1) {
129
        difference.push(firstArray[i]);
130
      }
131
      
132
    }
133
    return difference;
134
  }
135
  
136
  public saveSubjects() {
137
    if (!Session.isLoggedIn()) {
138
      this._router.navigate(['/user-info'],
139
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
140
    } else {
141
      if (this.communityId != null && this.communityId !== '') {
142
        this.showLoading = true;
143
        const subjectsToDeleteAr = this.getSubjectsExistOnlyInFirst(this.selectedSubjects, this.myForm.getRawValue());
144
        const subjectsToAddAr = this.getSubjectsExistOnlyInFirst(this.myForm.getRawValue(), this.selectedSubjects);
145
        const subjectsToDelete = this.getNonEmptyItems(subjectsToDeleteAr);
146
        const subjectsToAdd = this.getNonEmptyItems(subjectsToAddAr);
147
        if (subjectsToAdd.length > 0 && subjectsToDelete.length > 0) {
148
          const obs = concat(this._subjectsService.addSubjects(
149
            this.properties.communityAPI + this.communityId + '/subjects', subjectsToAdd),
150
            this._subjectsService.removeSubjects(
151
              this.properties.communityAPI + this.communityId + '/subjects', subjectsToDelete));
152
          this.subscriptions.push(obs.subscribe(res => {
153
              if (res['method'] === 'delete') {
154
                this.afterUpdateActions(res, "updated");
155
              }
156
            },
157
            error => this.handleUpdateError('System error updating subjects', error)
158
          ));
159
        } else if (subjectsToAdd.length > 0) {
160
          this.subscriptions.push(this._subjectsService.addSubjects(
161
            this.properties.communityAPI + this.communityId + '/subjects', subjectsToAdd).subscribe(res => {
162
              this.afterUpdateActions(res, "added");
163
            },
164
            error => this.handleUpdateError('System error updating subjects', error)
165
          ));
166
        } else if (subjectsToDelete.length > 0) {
167
          this.subscriptions.push(this._subjectsService.removeSubjects(
168
            this.properties.communityAPI + this.communityId + '/subjects', subjectsToDelete).subscribe(res => {
169
              this.afterUpdateActions(res, "deleted");
170
            },
171
            error => this.handleUpdateError('System error updating subjects', error)
172
          ));
173
        }
174
      }
175
    }
176
  }
177
  
178
  handleUpdateError(message: string, error) {
179
    UIkit.notification(message, {
180
      status: 'danger',
181
      timeout: 6000,
182
      pos: 'bottom-right'
183
    });
184
    this.showLoading = false;
185
  }
186
  
187
  afterUpdateActions(res, message: string) {
188
    this._communityService.setCommunity(this._communityService.parseCommunity(res));
189
    this.community.subjects = res['subjects'];
190
    this.originalSubjects = [];
191
    for (let i = 0; i < this.community.subjects.length; i++) {
192
      this.originalSubjects.push(this.community.subjects[i]);
193
    }
194
    this.page = 1;
195
    this.community.subjects = this.originalSubjects.filter(subject => {
196
      return subject.toLowerCase().indexOf(this.filterForm.value.toLowerCase()) != -1
197
    });
198
    UIkit.notification('Subjects successfully ' + message + '!', {
199
      status: 'success',
200
      timeout: 6000,
201
      pos: 'bottom-right'
202
    });
203
    this.showLoading = false;
204
  }
205
  
206
  
207
  private getNonEmptyItems(data: string[]): string[] {
208
    const length = data.length;
209
    const arrayNonEmpty = new Array<string>();
210
    let j = 0;
211
    for (let i = 0; i < length; i++) {
212
      if (this.isEmpty(data[i])) {
213
      } else if (this.isNonEmpty(data[i])) {
214
        arrayNonEmpty[j] = data[i];
215
        j++;
216
      }
217
    }
218
    return arrayNonEmpty;
219
  }
220
  
221
  
222
  private isEmpty(data: string): boolean {
223
    if (data !== undefined && !data.replace(/\s/g, '').length) {
224
      return true;
225
    } else {
226
      return false;
227
    }
228
  }
229
  
230
  private isNonEmpty(data: string): boolean {
231
    if (data !== undefined && data != null) {
232
      return true;
233
    } else {
234
      return false;
235
    }
236
  }
237
  
238
  public addSubjectInForm() {
239
    this.myForm.push(new FormControl(''));
240
  }
241
  
242
  public removeSubjectInForm(i: number) {
243
    this.myForm.removeAt(i);
244
  }
245
  
246
  public reset(subjects: string[]) {
247
    this.myForm = new FormArray([]);
248
    for (let subject in subjects) {
249
      this.myForm.push(new FormControl(''));
250
    }
251
    this.myForm.patchValue(subjects);
252
  }
253
  
254
  newSubject() {
255
    this.isEditModal = false;
256
    this.selectedSubjects = [];
257
    this.reset([""]);
258
    this.formModalOpen('Add Subject', 'Save');
259
  }
260
  
261
  public editSubject(subject: string) {
262
    this.isEditModal = true;
263
    this.selectedSubjects = [subject];
264
    this.reset([subject]);
265
    this.formModalOpen('Edit Subject', 'Save');
266
  }
267
  
268
  
269
  private formModalOpen(title: string, yesBtn: string) {
270
    if (!Session.isLoggedIn()) {
271
      this._router.navigate(['/user-info'], {
272
        queryParams: {
273
          "errorCode": LoginErrorCodes.NOT_VALID,
274
          "redirectUrl": this._router.url
275
        }
276
      });
277
    } else {
278
      this.editModal.okButtonLeft = false;
279
      this.editModal.cancelButton = true;
280
      this.editModal.okButton = true;
281
      this.editModal.alertTitle = title;
282
      this.editModal.okButtonText = yesBtn;
283
      this.editModal.open();
284
    }
285
  }
286
  
287
  public onSearchClose() {
288
    this.selectedKeyword = this.filterForm.value;
289
  }
290
  
291
  public resetInput() {
292
    this.selectedKeyword = null;
293
    this.searchInputComponent.reset()
294
  }
295
}
(3-3/4)