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 '../sources-forms/datasource-new-interface-form.component';
12
import { from, of } from 'rxjs';
13
import { concatMap } from 'rxjs/operators';
14
import {
15
  formErrorRegisterRepo,
16
  formInfoLoading, formInterfacesLoading, loadingInterfacesError, loadingRepoError,
17
  noInterfacesSaved
18
} from '../../../domain/shared-messages';
19
import { DatasourceUpdateFormComponent } from '../sources-forms/datasource-update-form.component';
20
import { RegisterDatasourceSelectExistingComponent } from './register-datasource-select-existing.component';
21

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

    
30
  datasourceType: string;
31
  currentMode: string;
32
  datasourceId: string;
33
  repo: Repository;
34
  repoInterfaces: RepositoryInterface[] = [];
35

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

    
51
  @ViewChild('datasourcesByCountry')
52
  public datasourcesByCountry: RegisterDatasourceSelectExistingComponent;
53

    
54
  @ViewChild ('registerDatasource')
55
  registerDatasource: DatasourceUpdateFormComponent;
56

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

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

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

    
76

    
77
  getStep() {
78
    this.currentStep = 0;
79
    if (this.route.snapshot.queryParamMap.has('step')) {
80
      const stepName = this.route.snapshot.queryParamMap.get('step');
81
      if (stepName === 'basicInformation') {
82
        if (!this.datasourceId) {
83
          this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=selectDatasource`);
84
        } else {
85
          this.currentStep = 1;
86
        }
87
      } else if (stepName === 'interfaces') {
88
        if (!this.repo) {
89
          this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=selectDatasource`);
90
        } else {
91
          this.currentStep = 2;
92
        }
93
      } else if (stepName === 'finish') {
94
        this.currentStep = 3;
95
      }
96
    }
97
    this.rightHelperContent.ngOnInit();
98
    this.topHelperContent.ngOnInit();
99
    this.leftHelperContent.ngOnInit();
100
    this.bottomHelperContent.ngOnInit();
101
  }
102

    
103
  navigateToStep(step: string) {
104
    this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=${step}`);
105
      /*.then( () => {
106
          // this.getStep();
107
          this.rightHelperContent.ngOnInit();
108
          this.topHelperContent.ngOnInit();
109
          this.leftHelperContent.ngOnInit();
110
          this.bottomHelperContent.ngOnInit();
111
        }
112
      );*/
113
  }
114

    
115
  moveAStep() {
116
    this.errorMessage = '';
117
    if (this.currentStep === 0) {
118
      if (this.datasourcesByCountry.goToNextStep()) {
119
        console.log(`got datasource with id ${this.datasourceId}`);
120
        this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=basicInformation`);
121
      }
122
    } else if (this.currentStep === 1) {
123
      this.registerDatasource.updateRepo();
124
    } else if (this.currentStep === 2) {
125
      of(this.getInterfaces()).subscribe(
126
        () => {
127
          if (this.repoInterfaces.length > 0) {
128
            this.registerRepository();
129
          } else {
130
            this.errorMessage = noInterfacesSaved;
131
          }
132
        }
133
      );
134
    }
135
  }
136

    
137
  moveBackAStep() {
138
    this.errorMessage = '';
139
    if (this.currentStep === 1) {
140
      this.repoInterfaces = [];
141
      this.repo = null;
142
      this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=selectDatasource`);
143
    } else if (this.currentStep === 2) {
144
      of(this.getInterfaces()).subscribe(
145
        () => this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=basicInformation`)
146
      );
147
    }
148
  }
149

    
150
  addInterfaceToList(intrf?: RepositoryInterface) {
151
    const curIndex = this.dataForInterfaceComp.length;
152
    const curRepoInfo = { id: this.repo.id, datasourceType: this.repo.datasourceType,
153
      datasourceClass: this.repo.datasourceClass, registeredBy: this.repo.registeredBy };
154
    if (intrf) {
155
      this.dataForInterfaceComp.push([true, curIndex, curRepoInfo, intrf]);
156
    } else {
157
      this.dataForInterfaceComp.push([true, curIndex, curRepoInfo]);
158
    }
159
  }
160

    
161
  removeInterfaceFromList(i: number) {
162
    const tempArray = this.dataForInterfaceComp;
163
    this.dataForInterfaceComp = [];
164
    tempArray.splice(i, 1);
165
    this.dataForInterfaceComp = tempArray;
166
    console.log(JSON.stringify(this.dataForInterfaceComp));
167
  }
168

    
169
  getInterfaces() {
170
    this.repoInterfaces = [];
171
    for (const el of this.interfacesArray.toArray()) {
172
      const intrf = el.getInterface();
173
      if (intrf) {
174
        this.repoInterfaces.push(intrf);
175
        console.log(JSON.stringify(intrf));
176
      }
177
    }
178
    console.log('new interfaces is ', this.repoInterfaces);
179
  }
180

    
181
  fillInterfacesForms() {
182
    this.dataForInterfaceComp = [];
183
    if (this.repoInterfaces && (this.repoInterfaces.length > 0)) {
184
      for (let i = 0; i < this.repoInterfaces.length; i++) {
185
        this.dataForInterfaceComp.push([
186
          true, i,
187
          { id: this.repo.id,
188
            datasourceType: this.repo.datasourceType,
189
            datasourceClass: this.repo.datasourceClass,
190
            registeredBy: this.repo.registeredBy
191
          },
192
          this.repoInterfaces[i]
193
        ]);
194
      }
195
    } else {
196
      this.dataForInterfaceComp.push([
197
        true, 0,
198
        { id: this.repo.id,
199
          datasourceType: this.repo.datasourceType,
200
          datasourceClass: this.repo.datasourceClass,
201
          registeredBy: this.repo.registeredBy
202
        }
203
      ]);
204
    }
205
  }
206

    
207
  goToStep2(emitted: boolean) {
208
    if (emitted) {
209
      this.moveAStep();
210
    }
211
  }
212

    
213
  getRepoId(emitedId: string) {
214
    this.datasourceId = emitedId;
215
    this.getRepo();
216
  }
217

    
218
  getRepo() {
219
    this.loadingMessage = formInfoLoading;
220
    if (this.datasourceId) {
221
      this.repoService.getRepositoryById(this.datasourceId).subscribe(
222
        repo => {
223
          this.repo = repo;
224
        },
225
        error => {
226
          console.log(error);
227
          this.loadingMessage = '';
228
          this.errorMessage = loadingRepoError;
229
        },
230
        () => {
231
          this.loadingMessage = '';
232
        }
233
      );
234
    }
235
  }
236

    
237
  getUpdatedRepo(repo: Repository) {
238
    this.repo = repo;
239
    if (this.repoInterfaces.length === 0) {
240
      this.getRepoInterfaces();
241
    } else {
242
      of(this.fillInterfacesForms()).subscribe(
243
        () => this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=interfaces`)
244
      );
245
    }
246
  }
247

    
248
  getRepoInterfaces() {
249
    this.loadingMessage = formInterfacesLoading;
250
    this.errorMessage = '';
251
    this.repoService.getRepositoryInterface(this.datasourceId).subscribe(
252
      interfaces => {
253
        this.repoInterfaces = interfaces.sort( function(a, b) {
254
          if (a.id < b.id) {
255
            return -1;
256
          } else if (a.id > b.id) {
257
            return 1;
258
          } else {
259
            return 0;
260
          }
261
        });
262
        console.log(`the number of interfaces is ${this.repoInterfaces.length}`);
263
      },
264
      error => {
265
          console.log(error);
266
          this.errorMessage = loadingInterfacesError;
267
          this.loadingMessage = '';
268
        },
269
      () => {
270
        this.loadingMessage = '';
271
        of(this.fillInterfacesForms()).subscribe(
272
          () => this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=interfaces`)
273
        );
274
      }
275
    );
276
  }
277

    
278
  downloadLogo() {
279
    window.open('../../../../assets/imgs/3_0ValidatedLogo.png', '_blank', 'enabledstatus=0,toolbar=0,menubar=0,location=0');
280
  }
281

    
282
  // updateRepository() {
283
  //   if (this.repo) {
284
  //     this.loadingMessage = 'Saving changes';
285
  //     this.errorMessage = '';
286
  //     this.repoService.updateRepository(this.repo).subscribe(
287
  //       response => {
288
  //         console.log(`updateRepository responded: ${response.id}, ${response.registeredBy}`);
289
  //         this.repo = response;
290
  //       },
291
  //       error => {
292
  //         console.log(error);
293
  //         this.loadingMessage = '';
294
  //         this.errorMessage = formErrorRegisterRepo;
295
  //       },
296
  //       () => {
297
  //         this.saveNewInterfaces();
298
  //       }
299
  //     );
300
  //   }
301
  // }
302

    
303
  registerRepository() {
304
    if (this.repo) {
305
      this.loadingMessage = 'Saving changes';
306
      this.errorMessage = '';
307
      this.repoService.addRepository( this.repo.datasourceType, this.repo).subscribe(
308
        response => {
309
          console.log(`addRepository responded: ${response.id}, ${response.registeredBy}`);
310
          this.repo = response;
311
        },
312
        error => {
313
          console.log(error);
314
          this.loadingMessage = '';
315
          this.errorMessage = formErrorRegisterRepo;
316
        },
317
        () => {
318
          this.saveNewInterfaces();
319
        }
320
      );
321
    }
322
  }
323

    
324
  saveNewInterfaces() {
325
    if (this.repoInterfaces && (this.repoInterfaces.length > 0)) {
326
      from(this.repoInterfaces).pipe(
327
        concatMap(intrf => {
328
          if (intrf.id) {
329
            return this.repoService.updateInterface(this.repo.id, this.repo.registeredBy, intrf);
330
          } else {
331
            return this.repoService.addInterface(this.repo.datasourceType, this.repo.id, this.repo.registeredBy, intrf);
332
          }
333
        })
334
      ).subscribe(
335
        res => console.log('after save interfaces', JSON.stringify(res)),
336
        er => {
337
          console.log(er);
338
          this.loadingMessage = '';
339
          this.errorMessage = 'Not all changes were saved. Please try again';
340
        },
341
        () => {
342
          this.loadingMessage = '';
343
          this.datasourceId = null;
344
          this.repo = null;
345
          this.repoInterfaces = [];
346
          this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=finish`);
347
        }
348
      );
349
    }
350
  }
351
}
(4-4/10)