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
  ngOnInit() {
68
    if (this.datasourceType && this.currentMode) {
69
      // will execute getStep() every time there is a change in query params
70
      this.route.queryParams.subscribe(
71
        params => {
72
          this.getStep();
73
        }
74
      );
75
    }
76
  }
77

    
78

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

    
105
  moveAStep() {
106
    window.scrollTo(0, 0);
107
    this.errorMessage = '';
108
    if (this.currentStep === 0) {
109
      if (this.datasourcesByCountry.goToNextStep()) {
110
        console.log(`got datasource with id ${this.datasourceId}`);
111
        this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=basicInformation`);
112
      }
113
    } else if (this.currentStep === 1) {
114
      this.registerDatasource.updateRepo();
115
    } else if (this.currentStep === 2) {
116
      of(this.getInterfaces()).subscribe(
117
        errors => {
118
          if (errors > 0) {
119
            this.errorMessage = errorsInInterfaces;
120
            window.scrollTo(1, 1);
121
          } else {
122
            if (this.repoInterfaces.length > 0) {
123
              this.registerRepository();
124
            } else {
125
              this.errorMessage = noInterfacesSaved;
126
              window.scrollTo(1, 1);
127
            }
128
          }
129
        }
130
      );
131
    }
132
  }
133

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

    
148
  addInterfaceToList(intrf?: RepositoryInterface) {
149

    
150
    console.log('clicked add interface to list');
151

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

    
162
  removeInterfaceFromList(i: number) {
163
    const tempArray = this.dataForInterfaceComp;
164
    this.dataForInterfaceComp = [];
165
    if (tempArray[i] && tempArray[i][3] && tempArray[i][3].id) {
166
      this.interfacesToDelete.push(tempArray[i][3].id);
167
    }
168
    tempArray.splice(i, 1);
169
    this.dataForInterfaceComp = tempArray;
170
    console.log(JSON.stringify(this.dataForInterfaceComp));
171
  }
172

    
173
  getInterfaces() {
174
    // this.repoInterfaces = [];
175
    let invalidFormsCount = 0;
176
    for (const el of this.interfacesArray.toArray()) {
177
      const intrf = el.getInterface();
178
      if (intrf) {
179
        if (intrf.id && this.repoInterfaces.some(intr => intr.id === intrf.id)) {
180
          const i = this.repoInterfaces.findIndex( intr => intr.id === intrf.id );
181
          this.repoInterfaces[i] = intrf;
182
        } else {
183
          this.repoInterfaces.push(intrf);
184
        }
185
        console.log(JSON.stringify(intrf));
186
      } else {
187
        invalidFormsCount = invalidFormsCount + 1;
188
        const repo_interface = el.getCurrentValues();
189
        if (repo_interface.id && this.repoInterfaces.some(intr => intr.id === repo_interface.id)) {
190
          const i = this.repoInterfaces.findIndex( intr => intr.id === repo_interface.id );
191
          this.repoInterfaces[i] = repo_interface;
192
        } else {
193
          this.repoInterfaces.push(repo_interface);
194
        }
195
        console.log(JSON.stringify(repo_interface));
196
      }
197
    }
198
    console.log('new interfaces is ', this.repoInterfaces);
199
    return invalidFormsCount;
200
  }
201

    
202
  fillInterfacesForms() {
203
    this.dataForInterfaceComp = [];
204
    if (this.repoInterfaces && (this.repoInterfaces.length > 0)) {
205
      for (let i = 0; i < this.repoInterfaces.length; i++) {
206
        this.dataForInterfaceComp.push([
207
          true, i,
208
          { id: this.repo.id,
209
            datasourceType: this.repo.datasourceType,
210
            datasourceClass: this.repo.datasourceClass,
211
            registeredBy: this.repo.registeredBy
212
          },
213
          this.repoInterfaces[i]
214
        ]);
215
      }
216
    } else {
217
      this.dataForInterfaceComp.push([
218
        true, 0,
219
        { id: this.repo.id,
220
          datasourceType: this.repo.datasourceType,
221
          datasourceClass: this.repo.datasourceClass,
222
          registeredBy: this.repo.registeredBy
223
        }
224
      ]);
225
    }
226
  }
227

    
228
  goToStep2(emitted: boolean) {
229
    if (emitted) {
230
      this.moveAStep();
231
    }
232
  }
233

    
234
  getRepoId(emitedId: string) {
235
    this.datasourceId = emitedId;
236
    this.getRepo();
237
  }
238

    
239
  getRepo() {
240
    this.loadingMessage = formInfoLoading;
241
    if (this.datasourceId) {
242
      this.repoService.getRepositoryById(this.datasourceId).subscribe(
243
        repo => {
244
          this.repo = repo;
245
        },
246
        error => {
247
          console.log(error);
248
          this.loadingMessage = '';
249
          this.errorMessage = loadingRepoError;
250
        },
251
        () => {
252
          this.loadingMessage = '';
253
        }
254
      );
255
    }
256
  }
257

    
258
  getUpdatedRepo(repo: Repository) {
259
    this.repo = repo;
260
    if (this.repoInterfaces.length === 0) {
261
      this.getRepoInterfaces();
262
    } else {
263
      of(this.fillInterfacesForms()).subscribe(
264
        () => this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=interfaces`)
265
      );
266
    }
267
  }
268

    
269
  getRepoInterfaces() {
270
    this.loadingMessage = formInterfacesLoading;
271
    this.errorMessage = '';
272
    this.repoService.getRepositoryInterface(this.datasourceId).subscribe(
273
      interfaces => {
274
        this.repoInterfaces = interfaces.sort( function(a, b) {
275
          if (a.id < b.id) {
276
            return -1;
277
          } else if (a.id > b.id) {
278
            return 1;
279
          } else {
280
            return 0;
281
          }
282
        });
283
        console.log(`the number of interfaces is ${this.repoInterfaces.length}`);
284
      },
285
      error => {
286
          console.log(error);
287
          this.errorMessage = loadingInterfacesError;
288
          this.loadingMessage = '';
289
          window.scrollTo(1, 1);
290
        },
291
      () => {
292
        this.loadingMessage = '';
293
        of(this.fillInterfacesForms()).subscribe(
294
          () => this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=interfaces`)
295
        );
296
      }
297
    );
298
  }
299

    
300
  downloadLogo() {
301
    window.open('../../../../assets/imgs/3_0ValidatedLogo.png', '_blank', 'enabledstatus=0,toolbar=0,menubar=0,location=0');
302
  }
303

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

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