Project

General

Profile

1
/*
2
*  created by myrto on 19/12/2018
3
*/
4

    
5
import { Component, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core';
6
import { Repository, RepositoryInterface } from '../../../domain/typeScriptClasses';
7
import { ActivatedRoute, Router } from '@angular/router';
8
import { FormBuilder } from '@angular/forms';
9
import { AsideHelpContentComponent, HelpContentComponent } from '../../../shared/reusablecomponents/help-content.component';
10
import { RepositoryService } from '../../../services/repository.service';
11
import { DatasourceNewInterfaceFormComponent } from '../../../shared/reusablecomponents/sources-forms/datasource-new-interface-form.component';
12
import { from, of } from 'rxjs';
13
import { concatMap } from 'rxjs/operators';
14
import {
15
  errorsInInterfaces,
16
  formErrorRegisterRepo,
17
  formInfoLoading, formInterfacesLoading, loadingInterfacesError, loadingRepoError,
18
  noInterfacesSaved
19
} from '../../../domain/shared-messages';
20
import { DatasourceUpdateFormComponent } from '../../../shared/reusablecomponents/sources-forms/datasource-update-form.component';
21
import { RegisterDatasourceSelectExistingComponent } from './register-datasource-select-existing.component';
22
import {DatasourceUpdateTermsFormComponent} from '../../../shared/reusablecomponents/sources-forms/datasource-update-terms-form.component';
23

    
24
@Component({
25
  selector: 'app-register-existing-datasource',
26
  templateUrl: './register-existing-datasource.component.html'
27
})
28
export class RegisterExistingDatasourceComponent implements OnInit {
29
  loadingMessage: string;
30
  errorMessage: string;
31

    
32
  datasourceType: string;
33
  currentMode: string;
34
  datasourceId: string;
35
  repo: Repository;
36
  repoInterfaces: RepositoryInterface[] = [];
37
  interfacesToDelete: string[] = [];
38
  // comments: string;
39

    
40
  /* queryParams are used to follow the steps without refreshing the page
41
   * This was needed for Help Service [which sends back info according to the current router.url].
42
   * The param that is used is 'step' and the values are: 'selectDatasource','basicInformation','interfaces','finish'
43
   * currentStep represents the number of the current step
44
   */
45
  currentStep: number;
46
  @ViewChild('topHelperContent', { static: true })
47
  public topHelperContent: HelpContentComponent;
48
  @ViewChild('leftHelperContent', { static: true })
49
  public leftHelperContent: AsideHelpContentComponent;
50
  @ViewChild('rightHelperContent', { static: true })
51
  public rightHelperContent: AsideHelpContentComponent;
52
  @ViewChild('bottomHelperContent', { static: true })
53
  public bottomHelperContent: HelpContentComponent;
54

    
55
  @ViewChild('datasourcesByCountry')
56
  public datasourcesByCountry: RegisterDatasourceSelectExistingComponent;
57

    
58
  @ViewChild('registerDatasource')
59
  registerDatasource: DatasourceUpdateFormComponent;
60

    
61
  @ViewChild('interfaceComments')
62
  interfaceComments: DatasourceNewInterfaceFormComponent;
63

    
64
  @ViewChildren('interfacesArray') interfacesArray: QueryList<DatasourceNewInterfaceFormComponent>;
65
  dataForInterfaceComp: any[] = [];
66

    
67
  @ViewChild('updateTermsForm')
68
  updateTermsForm: DatasourceUpdateTermsFormComponent;
69

    
70
  constructor(private fb: FormBuilder,
71
              private route: ActivatedRoute,
72
              private router: Router,
73
              private repoService: RepositoryService) {}
74

    
75
  ngOnInit() {
76
    if (this.datasourceType && this.currentMode) {
77
      // will execute getStep() every time there is a change in query params
78
      this.route.queryParams.subscribe(
79
        params => {
80
          this.getStep();
81
        }
82
      );
83
    }
84
  }
85

    
86

    
87
  getStep() {
88
    this.currentStep = 0;
89
    if (this.route.snapshot.queryParamMap.has('step')) {
90
      const stepName = this.route.snapshot.queryParamMap.get('step');
91
      if (stepName === 'basicInformation') {
92
        if (!this.datasourceId) {
93
          this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=selectDatasource`);
94
        } else {
95
          this.currentStep = 1;
96
        }
97
      } else if (stepName === 'interfaces') {
98
        if (!this.repo) {
99
          this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=selectDatasource`);
100
        } else {
101
          this.currentStep = 2;
102
        }
103
        } else if (stepName === 'termsOfUse') {
104
          if (!this.interfacesArray) {
105
            this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=selectDatasource`);
106
          } else {
107
            this.currentStep = 3;
108
          }
109
        } else if (stepName === 'finish') {
110
          this.currentStep = 4;
111
      }
112
    }
113
    this.rightHelperContent.ngOnInit();
114
    this.topHelperContent.ngOnInit();
115
    this.leftHelperContent.ngOnInit();
116
    this.bottomHelperContent.ngOnInit();
117
  }
118

    
119
  moveAStep() {
120
    window.scrollTo(0, 0);
121
    this.errorMessage = '';
122
    if (this.currentStep === 0) {
123
      if (this.datasourcesByCountry.goToNextStep()) {
124
        console.log(`got datasource with id ${this.datasourceId}`);
125
        this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=basicInformation`);
126
      }
127
    } else if (this.currentStep === 1) {
128
      this.registerDatasource.updateRepo();
129
    } else if (this.currentStep === 2) {
130
      of(this.getInterfaces()).subscribe(
131
        errors => {
132
          if (errors > 0) {
133
            this.errorMessage = errorsInInterfaces;
134
            window.scrollTo(1, 1);
135
          } else {
136
            if (this.repoInterfaces.length > 0) {
137
              this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=termsOfUse`);
138
            } else {
139
              this.errorMessage = noInterfacesSaved;
140
              window.scrollTo(1, 1);
141
            }
142
          }
143
        }
144
      );
145
      } else if (this.currentStep === 3) {
146
      this.registerRepository();
147
    }
148
  }
149

    
150
  moveBackAStep() {
151
    window.scrollTo(0, 0);
152
    this.errorMessage = '';
153
    if (this.currentStep === 1) {
154
      this.repoInterfaces = [];
155
      this.repo = null;
156
      this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=selectDatasource`);
157
    } else if (this.currentStep === 2) {
158
      of(this.getInterfaces()).subscribe(
159
        () => this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=basicInformation`)
160
      );
161
      } else if (this.currentStep === 3) {
162
      this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=interfaces`);
163
    }
164
  }
165

    
166
  addInterfaceToList(intrf?: RepositoryInterface) {
167

    
168
    console.log('clicked add interface to list');
169

    
170
    const curIndex = this.dataForInterfaceComp.length;
171
    const curRepoInfo = { id: this.repo.id, datasourceType: this.repo.datasourceType,
172
      datasourceClass: this.repo.datasourceClass, registeredBy: this.repo.registeredBy };
173
    if (intrf) {
174
      this.dataForInterfaceComp.push([true, curIndex, curRepoInfo, intrf]);
175
    } else {
176
      this.dataForInterfaceComp.push([true, curIndex, curRepoInfo]);
177
    }
178
  }
179

    
180
  removeInterfaceFromList(i: number) {
181
    const tempArray = this.dataForInterfaceComp;
182
    this.dataForInterfaceComp = [];
183
    if (tempArray[i] && tempArray[i][3] && tempArray[i][3].id) {
184
      this.interfacesToDelete.push(tempArray[i][3].id);
185
    }
186
    tempArray.splice(i, 1);
187
    this.dataForInterfaceComp = tempArray;
188
    console.log(JSON.stringify(this.dataForInterfaceComp));
189
  }
190

    
191
  getInterfaces() {
192
    // this.repoInterfaces = [];
193
    let invalidFormsCount = 0;
194
    for (const el of this.interfacesArray.toArray()) {
195
      const intrf = el.getInterface();
196
      if (intrf) {
197
        if (intrf.id && this.repoInterfaces.some(intr => intr.id === intrf.id)) {
198
          const i = this.repoInterfaces.findIndex( intr => intr.id === intrf.id );
199
          this.repoInterfaces[i] = intrf;
200
        } else {
201
          this.repoInterfaces.push(intrf);
202
        }
203
        console.log(JSON.stringify(intrf));
204
      } else {
205
        invalidFormsCount = invalidFormsCount + 1;
206
        const repo_interface = el.getCurrentValues();
207
        if (repo_interface.id && this.repoInterfaces.some(intr => intr.id === repo_interface.id)) {
208
          const i = this.repoInterfaces.findIndex( intr => intr.id === repo_interface.id );
209
          this.repoInterfaces[i] = repo_interface;
210
        } else {
211
          this.repoInterfaces.push(repo_interface);
212
        }
213
        console.log(JSON.stringify(repo_interface));
214
      }
215
    }
216
    console.log('new interfaces is ', this.repoInterfaces);
217
    return invalidFormsCount;
218
  }
219

    
220
  fillInterfacesForms() {
221
    this.dataForInterfaceComp = [];
222
    if (this.repoInterfaces && (this.repoInterfaces.length > 0)) {
223
      for (let i = 0; i < this.repoInterfaces.length; i++) {
224
        this.dataForInterfaceComp.push([
225
          true, i,
226
          { id: this.repo.id,
227
            datasourceType: this.repo.datasourceType,
228
            datasourceClass: this.repo.datasourceClass,
229
            registeredBy: this.repo.registeredBy
230
          },
231
          this.repoInterfaces[i]
232
        ]);
233
      }
234
    } else {
235
      this.dataForInterfaceComp.push([
236
        true, 0,
237
        { id: this.repo.id,
238
          datasourceType: this.repo.datasourceType,
239
          datasourceClass: this.repo.datasourceClass,
240
          registeredBy: this.repo.registeredBy
241
        }
242
      ]);
243
    }
244
  }
245

    
246
  goToStep2(emitted: boolean) {
247
    if (emitted) {
248
      this.moveAStep();
249
    }
250
  }
251

    
252
  getRepoId(emitedId: string) {
253
    this.datasourceId = emitedId;
254
    this.getRepo();
255
  }
256

    
257
  getRepo() {
258
    this.loadingMessage = formInfoLoading;
259
    if (this.datasourceId) {
260
      this.repoService.getRepositoryById(this.datasourceId).subscribe(
261
        repo => {
262
          this.repo = repo;
263
        },
264
        error => {
265
          console.log(error);
266
          this.loadingMessage = '';
267
          this.errorMessage = loadingRepoError;
268
        },
269
        () => {
270
          this.loadingMessage = '';
271
        }
272
      );
273
    }
274
  }
275

    
276
  getUpdatedRepo(repo: Repository) {
277
    console.log('getUpdatedRepo(repo: Repository)');
278
    this.repo = repo;
279
    if (this.repoInterfaces.length === 0) {
280
      this.getRepoInterfaces();
281
    } else {
282
      of(this.fillInterfacesForms()).subscribe(
283
        () => this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=interfaces`)
284
      );
285
    }
286
  }
287

    
288
  getRepoInterfaces() {
289
    this.loadingMessage = formInterfacesLoading;
290
    this.errorMessage = '';
291
    this.repoService.getRepositoryInterface(this.datasourceId).subscribe(
292
      interfaces => {
293
        this.repoInterfaces = interfaces.sort( function(a, b) {
294
          if (a.id < b.id) {
295
            return -1;
296
          } else if (a.id > b.id) {
297
            return 1;
298
          } else {
299
            return 0;
300
          }
301
        });
302
        console.log(`the number of interfaces is ${this.repoInterfaces.length}`);
303
      },
304
      error => {
305
          console.log(error);
306
          this.errorMessage = loadingInterfacesError;
307
          this.loadingMessage = '';
308
          window.scrollTo(1, 1);
309
        },
310
      () => {
311
        this.loadingMessage = '';
312
        of(this.fillInterfacesForms()).subscribe(
313
          () => this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=interfaces`)
314
        );
315
      }
316
    );
317
  }
318

    
319
  //recheck if needed
320
  getTerms(repo: Repository) {
321
    this.repo = repo;
322
  }
323

    
324
  downloadLogo() {
325
    window.open('../../../../assets/imgs/3_0ValidatedLogo.png', '_blank', 'enabledstatus=0,toolbar=0,menubar=0,location=0');
326
  }
327

    
328
  registerRepository() {
329
    console.log('in registerRepository, step ===', this.currentStep);
330
    if (this.repo) {
331
      this.loadingMessage = 'Saving changes';
332
      this.errorMessage = '';
333
      console.log('reg this.repo', this.repo);
334
      this.repoService.addRepository( this.repo.datasourceType, this.repo).subscribe(
335
        response => {
336
          console.log(`addRepository responded: ${response.id}, ${response.registeredBy}`);
337
          this.repo = response;
338
        },
339
        error => {
340
          console.log(error);
341
          this.loadingMessage = '';
342
          this.errorMessage = formErrorRegisterRepo;
343
          window.scrollTo(1, 1);
344
        },
345
        () => {
346
          this.saveNewInterfaces();
347
        }
348
      );
349
    }
350
  }
351

    
352
  saveNewInterfaces() {
353
    if (this.repoInterfaces && (this.repoInterfaces.length > 0)) {
354
      from(this.repoInterfaces).pipe(
355
        concatMap(intrf => {
356
          if (intrf.id) {
357
            let req;
358
            if (this.interfacesToDelete.some(id => id === intrf.id)) {
359
              req = this.repoService.deleteInterface(intrf.id, this.repo.registeredBy);
360
            } else {
361
              // console.log('comments', intrf.comments);
362
              req = this.repoService.updateInterface(this.repo.id, this.repo.registeredBy, intrf.comments, intrf);
363
            }
364
            return req;
365
          } else {
366
            // console.log('comments', intrf.comments);
367
            return this.repoService.addInterface(this.repo.datasourceType, this.repo.id, this.repo.registeredBy, intrf.comments, intrf);
368
          }
369
        })
370
      ).subscribe(
371
        res => console.log('after save interfaces', JSON.stringify(res)),
372
        er => {
373
          console.log(er);
374
          this.loadingMessage = '';
375
          this.errorMessage = 'Not all changes were saved. Please try again';
376
          window.scrollTo(1, 1);
377
        },
378
        () => {
379
          this.loadingMessage = '';
380
          this.datasourceId = null;
381
          this.repo = null;
382
          this.repoInterfaces = [];
383
          this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=finish`);
384
        }
385
      );
386
    }
387
  }
388
}
(4-4/11)