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
  formInfoLoading, formInterfacesLoading, loadingInterfacesError, loadingRepoError,
16
  noInterfacesSaved
17
} from '../../../domain/shared-messages';
18
import { DatasourceUpdateFormComponent } from '../sources-forms/datasource-update-form.component';
19
import { RegisterDatasourceSelectExistingComponent } from './register-datasource-select-existing.component';
20

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

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

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

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

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

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

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

    
64
  ngOnInit() {
65
    if (this.datasourceType && this.currentMode) {
66
      this.getStep();
67
    }
68
  }
69

    
70

    
71
  getStep() {
72
    this.currentStep = 0;
73
    if (this.route.snapshot.queryParamMap.has('step')) {
74
      const stepName = this.route.snapshot.queryParamMap.get('step');
75
      if (stepName === 'basicInformation') {
76
        if (!this.datasourceId) {
77
          this.navigateToStep('selectDatasource');
78
        } else {
79
          this.currentStep = 1;
80
        }
81
      } else if (stepName === 'interfaces') {
82
        if (!this.repo) {
83
          this.navigateToStep('selectDatasource');
84
        } else {
85
          this.currentStep = 2;
86
        }
87
      } else if (stepName === 'finish') {
88
        this.currentStep = 3;
89
      }
90
    }
91
  }
92

    
93
  navigateToStep(step: string) {
94
    this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=${step}`)
95
      .then( () => {
96
          this.getStep();
97
          this.rightHelperContent.ngOnInit();
98
          this.topHelperContent.ngOnInit();
99
          this.leftHelperContent.ngOnInit();
100
          this.bottomHelperContent.ngOnInit();
101
        }
102
      );
103
  }
104

    
105
  moveAStep() {
106
    this.errorMessage = '';
107
    if (this.currentStep === 0) {
108
      if (this.datasourcesByCountry.goToNextStep()) {
109
        console.log(`got datasource with id ${this.datasourceId}`);
110
        this.navigateToStep('basicInformation');
111
      }
112
    } else if (this.currentStep === 1) {
113
      this.registerDatasource.updateRepo();
114
    } else if (this.currentStep === 2) {
115
      of(this.getInterfaces()).subscribe(
116
        () => {
117
          if (this.repoInterfaces.length > 0) {
118
            this.updateRepository();
119
          } else {
120
            this.errorMessage = noInterfacesSaved;
121
          }
122
        }
123
      );
124
    }
125
  }
126

    
127
  moveBackAStep() {
128
    this.errorMessage = '';
129
    if (this.currentStep === 1) {
130
      this.repoInterfaces = [];
131
      this.repo = null;
132
      this.navigateToStep('selectDatasource');
133
    } else if (this.currentStep === 2) {
134
      of(this.getInterfaces()).subscribe(
135
        () => this.navigateToStep('basicInformation')
136
      );
137
    }
138
  }
139

    
140
  addInterfaceToList(intrf?: RepositoryInterface) {
141
    const curIndex = this.dataForInterfaceComp.length;
142
    const curRepoInfo = { id: this.repo.id, datasourceType: this.repo.datasourceType,
143
      datasourceClass: this.repo.datasourceType, registeredBy: this.repo.registeredBy };
144
    if (intrf) {
145
      this.dataForInterfaceComp.push([true, curIndex, curRepoInfo, intrf]);
146
    } else {
147
      this.dataForInterfaceComp.push([true, curIndex, curRepoInfo]);
148
    }
149
  }
150

    
151
  removeInterfaceFromList(i: number) {
152
    const tempArray = this.dataForInterfaceComp;
153
    this.dataForInterfaceComp = [];
154
    tempArray.splice(i, 1);
155
    this.dataForInterfaceComp = tempArray;
156
    console.log(JSON.stringify(this.dataForInterfaceComp));
157
  }
158

    
159
  getInterfaces() {
160
    this.repoInterfaces = [];
161
    for (const el of this.interfacesArray.toArray()) {
162
      const intrf = el.getInterface();
163
      if (intrf) {
164
        this.repoInterfaces.push(intrf);
165
        console.log(JSON.stringify(intrf));
166
      }
167
    }
168
    console.log('new interfaces is ', this.repoInterfaces);
169
  }
170

    
171
  fillInterfacesForms() {
172
    this.dataForInterfaceComp = [];
173
    if (this.repoInterfaces && (this.repoInterfaces.length > 0)) {
174
      for (let i = 0; i < this.repoInterfaces.length; i++) {
175
        this.dataForInterfaceComp.push([
176
          true, i,
177
          { id: this.repo.id,
178
            datasourceType: this.repo.datasourceType,
179
            datasourceClass: this.repo.datasourceType,
180
            registeredBy: this.repo.registeredBy
181
          },
182
          this.repoInterfaces[i]
183
        ]);
184
      }
185
    } else {
186
      this.dataForInterfaceComp.push([
187
        true, 0,
188
        { id: this.repo.id,
189
          datasourceType: this.repo.datasourceType,
190
          datasourceClass: this.repo.datasourceType,
191
          registeredBy: this.repo.registeredBy
192
        }
193
      ]);
194
    }
195
  }
196

    
197
  goToStep2(emitted: boolean) {
198
    if (emitted) {
199
      this.moveAStep();
200
    }
201
  }
202

    
203
  getRepoId(emitedId: string) {
204
    this.datasourceId = emitedId;
205
    this.getRepo();
206
  }
207

    
208
  getRepo() {
209
    this.loadingMessage = formInfoLoading;
210
    if (this.datasourceId) {
211
      this.repoService.getRepositoryById(this.datasourceId).subscribe(
212
        repo => {
213
          this.repo = repo;
214
        },
215
        error => {
216
          console.log(error);
217
          this.loadingMessage = '';
218
          this.errorMessage = loadingRepoError;
219
        },
220
        () => {
221
          this.loadingMessage = '';
222
        }
223
      );
224
    }
225
  }
226

    
227
  getUpdatedRepo(repo: Repository) {
228
    this.repo = repo;
229
    if (this.repoInterfaces.length === 0) {
230
      this.getRepoInterfaces();
231
    } else {
232
      of(this.fillInterfacesForms()).subscribe(
233
        () => this.navigateToStep('interfaces')
234
      );
235
    }
236
  }
237

    
238
  getRepoInterfaces() {
239
    this.loadingMessage = formInterfacesLoading;
240
    this.errorMessage = '';
241
    this.repoService.getRepositoryInterface(this.datasourceId).subscribe(
242
      interfaces => {
243
        this.repoInterfaces = interfaces.sort( function(a, b) {
244
          if (a.id < b.id) {
245
            return -1;
246
          } else if (a.id > b.id) {
247
            return 1;
248
          } else {
249
            return 0;
250
          }
251
        });
252
        console.log(`the number of interfaces is ${this.repoInterfaces.length}`);
253
      },
254
      error => {
255
          console.log(error);
256
          this.errorMessage = loadingInterfacesError;
257
          this.loadingMessage = '';
258
        },
259
      () => {
260
        this.loadingMessage = '';
261
        of(this.fillInterfacesForms()).subscribe(
262
          () => this.navigateToStep('interfaces')
263
        );
264
      }
265
    );
266
  }
267

    
268
  downloadLogo() {
269
    window.open('../../../../assets/imgs/3_0ValidatedLogo.png', '_blank', 'enabledstatus=0,toolbar=0,menubar=0,location=0');
270
  }
271

    
272
  updateRepository() {
273
    if (this.repo) {
274
      this.loadingMessage = 'Saving changes';
275
      this.errorMessage = '';
276
      this.repoService.updateRepository(this.repo).subscribe(
277
        response => {
278
          console.log(`updateRepository responded: ${response.id}, ${response.registeredBy}`);
279
          this.repo = response;
280
        },
281
        error => {
282
          console.log(error);
283
          this.loadingMessage = '';
284
          this.errorMessage = 'The changes could not be saved';
285
        },
286
        () => {
287
          this.saveNewInterfaces();
288
        }
289
      );
290
    }
291
  }
292

    
293
  saveNewInterfaces() {
294
    if (this.repoInterfaces && (this.repoInterfaces.length > 0)) {
295
      from(this.repoInterfaces).pipe(
296
        concatMap(intrf => {
297
          if (intrf.id) {
298
            return this.repoService.updateInterface(this.repo.id, this.repo.registeredBy, intrf);
299
          } else {
300
            return this.repoService.addInterface(this.repo.datasourceType, this.repo.id, this.repo.registeredBy, intrf);
301
          }
302
        })
303
      ).subscribe(
304
        res => console.log('after save interfaces', JSON.stringify(res)),
305
        er => {
306
          console.log(er);
307
          this.loadingMessage = '';
308
          this.errorMessage = 'Not all changes were saved. Please try again';
309
        },
310
        () => {
311
          this.loadingMessage = '';
312
          this.navigateToStep('finish');
313
        }
314
      );
315
    }
316
  }
317
}
(4-4/10)