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

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

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

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

    
59
  @ViewChildren('interfacesArray') interfacesArray: QueryList<DatasourceNewInterfaceFormComponent>;
60
  dataForInterfaceComp: any[] = [];
61

    
62
  constructor(private fb: FormBuilder,
63
              private route: ActivatedRoute,
64
              private router: Router,
65
              private repoService: RepositoryService) {}
66

    
67
  // @ViewChild('updateTermsForm')
68

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

    
80

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

    
116
  moveAStep() {
117
    window.scrollTo(0, 0);
118
    this.errorMessage = '';
119
    if (this.currentStep === 0) {
120
      if (this.datasourcesByCountry.goToNextStep()) {
121
        console.log(`got datasource with id ${this.datasourceId}`);
122
        this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=basicInformation`);
123
      }
124
    } else if (this.currentStep === 1) {
125
      this.registerDatasource.updateRepo();
126
    } else if (this.currentStep === 2) {
127
      of(this.getInterfaces()).subscribe(
128
        errors => {
129
          if (errors > 0) {
130
            this.errorMessage = errorsInInterfaces;
131
            window.scrollTo(1, 1);
132
          } else {
133
            if (this.repoInterfaces.length > 0) {
134
              this.registerRepository();
135
// ToU: replace above line with the comment below
136
              // this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=termsOfUse`);
137
            } else {
138
              this.errorMessage = noInterfacesSaved;
139
              window.scrollTo(1, 1);
140
            }
141
          }
142
        }
143
      );
144
      // ToU: uncomment these lines
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
      // ToU: uncomment these lines
162
      // } else if (this.currentStep === 3) {
163
    //   this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=interfaces`);
164
    }
165
  }
166

    
167
  addInterfaceToList(intrf?: RepositoryInterface) {
168

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

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

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

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

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

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

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

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

    
277
  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
  downloadLogo() {
320
    window.open('../../../../assets/imgs/3_0ValidatedLogo.png', '_blank', 'enabledstatus=0,toolbar=0,menubar=0,location=0');
321
  }
322

    
323
  registerRepository() {
324
    if (this.repo) {
325
      this.loadingMessage = 'Saving changes';
326
      this.errorMessage = '';
327
      this.repoService.addRepository( this.repo.datasourceType, this.repo).subscribe(
328
        response => {
329
          console.log(`addRepository responded: ${response.id}, ${response.registeredBy}`);
330
          this.repo = response;
331
        },
332
        error => {
333
          console.log(error);
334
          this.loadingMessage = '';
335
          this.errorMessage = formErrorRegisterRepo;
336
          window.scrollTo(1, 1);
337
        },
338
        () => {
339
          this.saveNewInterfaces();
340
          // TODO: update terms when backend is ready, maybe POST with updateRepository
341
        }
342
      );
343
    }
344
  }
345

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