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
    const curIndex = this.dataForInterfaceComp.length;
168
    const curRepoInfo = { id: this.repo.id, datasourceType: this.repo.eoscDatasourceType,
169
      datasourceClass: this.repo.eoscDatasourceType, registeredBy: this.repo.registeredby };
170
    if (intrf) {
171
      this.dataForInterfaceComp.push([true, curIndex, curRepoInfo, intrf]);
172
    } else {
173
      this.dataForInterfaceComp.push([true, curIndex, curRepoInfo]);
174
    }
175
  }
176

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

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

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

    
243
  goToStep2(emitted: boolean) {
244
    if (emitted) {
245
      this.moveAStep();
246
    }
247
  }
248

    
249
  getRepoId(emitedId: string) {
250
    this.datasourceId = emitedId;
251
    this.getRepo();
252
  }
253

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

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

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

    
316
  // recheck if needed
317
  getTerms(repo: Repository) {
318
    this.repo = repo;
319
  }
320

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

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

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