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

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

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

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

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

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

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

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

    
66
  constructor(private fb: FormBuilder,
67
              private route: ActivatedRoute,
68
              private router: Router,
69
              private repoService: RepositoryService) {}
70

    
71
  // @ViewChild('updateTermsForm')
72

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

    
84

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

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

    
154
  moveBackAStep() {
155
    window.scrollTo(0, 0);
156
    this.errorMessage = '';
157
    if (this.currentStep === 1) {
158
      this.repoInterfaces = [];
159
      this.repo = null;
160
      this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=selectDatasource`);
161
    } else if (this.currentStep === 2) {
162
      of(this.getInterfaces()).subscribe(
163
        () => this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=basicInformation`)
164
      );
165
      // ToU: uncomment these lines
166
      // } else if (this.currentStep === 3) {
167
    //   this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=interfaces`);
168
    }
169
  }
170

    
171
  addInterfaceToList(intrf?: RepositoryInterface) {
172

    
173
    console.log('clicked add interface to list');
174

    
175
    const curIndex = this.dataForInterfaceComp.length;
176
    const curRepoInfo = { id: this.repo.id, datasourceType: this.repo.datasourceType,
177
      datasourceClass: this.repo.datasourceClass, registeredBy: this.repo.registeredBy };
178
    if (intrf) {
179
      this.dataForInterfaceComp.push([true, curIndex, curRepoInfo, intrf]);
180
    } else {
181
      this.dataForInterfaceComp.push([true, curIndex, curRepoInfo]);
182
    }
183
  }
184

    
185
  removeInterfaceFromList(i: number) {
186
    const tempArray = this.dataForInterfaceComp;
187
    this.dataForInterfaceComp = [];
188
    if (tempArray[i] && tempArray[i][3] && tempArray[i][3].id) {
189
      this.interfacesToDelete.push(tempArray[i][3].id);
190
    }
191
    tempArray.splice(i, 1);
192
    this.dataForInterfaceComp = tempArray;
193
    console.log(JSON.stringify(this.dataForInterfaceComp));
194
  }
195

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

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

    
251
  goToStep2(emitted: boolean) {
252
    if (emitted) {
253
      this.moveAStep();
254
    }
255
  }
256

    
257
  getRepoId(emitedId: string) {
258
    this.datasourceId = emitedId;
259
    this.getRepo();
260
  }
261

    
262
  getRepo() {
263
    this.loadingMessage = formInfoLoading;
264
    if (this.datasourceId) {
265
      this.repoService.getRepositoryById(this.datasourceId).subscribe(
266
        repo => {
267
          this.repo = repo;
268
        },
269
        error => {
270
          console.log(error);
271
          this.loadingMessage = '';
272
          this.errorMessage = loadingRepoError;
273
        },
274
        () => {
275
          this.loadingMessage = '';
276
        }
277
      );
278
    }
279
  }
280

    
281
  getUpdatedRepo(repo: Repository) {
282
    this.repo = repo;
283
    if (this.repoInterfaces.length === 0) {
284
      this.getRepoInterfaces();
285
    } else {
286
      of(this.fillInterfacesForms()).subscribe(
287
        () => this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=interfaces`)
288
      );
289
    }
290
  }
291

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

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

    
327
  registerRepository() {
328
    if (this.repo) {
329
      this.loadingMessage = 'Saving changes';
330
      this.errorMessage = '';
331
      this.repoService.addRepository( this.repo.datasourceType, this.repo).subscribe(
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
          // TODO: update terms when backend is ready, maybe POST with updateRepository
345
        }
346
      );
347
    }
348
  }
349

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