Project

General

Profile

1
import { Component, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core';
2
import { Repository, RepositoryInterface } from '../../../domain/typeScriptClasses';
3
import { ActivatedRoute, Router } from '@angular/router';
4
import { FormBuilder } from '@angular/forms';
5
import { AsideHelpContentComponent, HelpContentComponent } from '../../../shared/reusablecomponents/help-content.component';
6
import { RepositoryService } from '../../../services/repository.service';
7
import { DatasourceCreateFormComponent } from '../../../shared/reusablecomponents/sources-forms/datasource-create-form.component';
8
import { DatasourceNewInterfaceFormComponent } from '../../../shared/reusablecomponents/sources-forms/datasource-new-interface-form.component';
9
import { from, of } from 'rxjs';
10
import { concatMap } from 'rxjs/operators';
11
import { errorsInInterfaces, formErrorRegisterRepo, noInterfacesSaved } from '../../../domain/shared-messages';
12

    
13
@Component({
14
  selector: 'app-register-new-datasource',
15
  templateUrl: './register-new-datasource.component.html'
16
})
17
export class RegisterNewDatasourceComponent implements OnInit {
18
  loadingMessage: string;
19
  errorMessage: string;
20

    
21
  datasourceType: string;
22
  repo: Repository = null;
23
  repoInterfaces: RepositoryInterface[] = [];
24
  interfacesToDelete: string[] = [];
25

    
26
  /* queryParams are used to follow the steps without refreshing the page
27
   * This was needed for Help Service [which sends back info according to the current router.url].
28
   * The param that is used is 'step' and the values are: 'basicInformation','interfaces','finish'
29
   * currentStep represents the number of the current step
30
   */
31
  currentStep: number;
32
  @ViewChild('topHelperContent')
33
  public topHelperContent: HelpContentComponent;
34
  @ViewChild('leftHelperContent')
35
  public leftHelperContent: AsideHelpContentComponent;
36
  @ViewChild('rightHelperContent')
37
  public rightHelperContent: AsideHelpContentComponent;
38
  @ViewChild('bottomHelperContent')
39
  public bottomHelperContent: HelpContentComponent;
40

    
41
  @ViewChild ('registerDatasource')
42
  registerDatasource: DatasourceCreateFormComponent;
43

    
44
  @ViewChildren('interfacesArray') interfacesArray: QueryList<DatasourceNewInterfaceFormComponent>;
45
  dataForInterfaceComp: any[] = [];
46

    
47
  constructor(private fb: FormBuilder,
48
              private route: ActivatedRoute,
49
              private router: Router,
50
              private repoService: RepositoryService) {}
51

    
52
  // @ViewChild('updateTermsForm')
53

    
54
  ngOnInit() {
55
    if (this.datasourceType) {
56

    
57
      // will execute getStep() every time there is a change in query params
58
      this.route.queryParams.subscribe(
59
        params => {
60
          this.getStep();
61
        }
62
      );
63
    }
64
  }
65

    
66

    
67
  getStep() {
68
    this.currentStep = 1;
69
    if (this.route.snapshot.queryParamMap.has('step')) {
70
      const stepName = this.route.snapshot.queryParamMap.get('step');
71
      if (stepName === 'basicInformation') {
72
        this.currentStep = 1;
73
      } else if (stepName === 'interfaces') {
74
        if (!this.repo) {
75
          this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=basicInformation`);
76
        } else {
77
          this.currentStep = 2;
78
        }
79
      } else if (stepName === 'finish') {
80
        this.currentStep = 3;
81
        // ToU: to enable ToU delete the 2 lines above and uncomment the section below
82
      /*} else if (stepName === 'termsOfUse') {
83
        if (this.interfacesArray && this.interfacesArray.length === 0) {
84
          this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=basicInformation`);
85
        } else {
86
          this.currentStep = 3;
87
        }
88
      } else if (stepName === 'finish') {
89
        this.currentStep = 4;*/
90
      }
91
    }
92
    this.rightHelperContent.ngOnInit();
93
    this.topHelperContent.ngOnInit();
94
    this.leftHelperContent.ngOnInit();
95
    this.bottomHelperContent.ngOnInit();
96
  }
97

    
98
  moveAStep() {
99
    this.errorMessage = '';
100
    if (this.currentStep === 1) {
101
      this.registerDatasource.registerDatasource();
102
    } else if (this.currentStep === 2) {
103
      of(this.getInterfaces()).subscribe(
104
        errors => {
105
          if (errors > 0) {
106
            this.errorMessage = errorsInInterfaces;
107
            window.scrollTo(1, 1);
108
          } else {
109
            if (this.repoInterfaces.length > 0) {
110
              this.addRepository();
111
// ToU: replace above line with the comment below
112
//               this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=termsOfUse`);
113
            } else {
114
              this.errorMessage = noInterfacesSaved;
115
              window.scrollTo(1, 1);
116
            }
117
          }
118
        }
119
      );
120
      // ToU: uncomment these lines
121
    // } else if ( this.currentStep === 3 ) {
122
    //   this.addRepository();
123
    }
124
  }
125

    
126
  moveBackAStep() {
127
    this.errorMessage = '';
128
    if (this.currentStep === 2) {
129
      of(this.getInterfaces()).subscribe(
130
        () => this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=basicInformation`)
131
      );
132
      // ToU: uncomment these lines
133
    // } else if (this.currentStep === 3) {
134
    //   this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=interfaces`);
135
    }
136
  }
137

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

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

    
157
  getInterfaces() {
158
    this.repoInterfaces = [];
159
    let invalidFormsCount = 0;
160
    for (const el of this.interfacesArray.toArray()) {
161
      const intrf = el.getInterface();
162
      if (intrf) {
163
        this.repoInterfaces.push(intrf);
164
        console.log(JSON.stringify(intrf));
165
      } else {
166
        invalidFormsCount = invalidFormsCount + 1;
167
        const repo_interface = el.getCurrentValues();
168
        this.repoInterfaces.push(repo_interface);
169
        console.log(JSON.stringify(repo_interface));
170
      }
171
    }
172
    console.log('new interfaces is ', this.repoInterfaces);
173
    return invalidFormsCount;
174
  }
175

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

    
202
  getCurrentRepo(repo: Repository) {
203
    this.repo = repo;
204
    of (this.fillInterfacesForms()).subscribe(
205
      () => this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=interfaces`)
206
    );
207
  }
208

    
209
  downloadLogo() {
210
    window.open('../../../../assets/imgs/3_0ValidatedLogo.png', '_blank', 'enabledstatus=0,toolbar=0,menubar=0,location=0');
211
  }
212

    
213
  addRepository() {
214
    if (this.repo) {
215
      this.loadingMessage = 'Saving changes';
216
      this.errorMessage = '';
217
      this.repoService.addRepository(this.repo.datasourceType, this.repo).subscribe(
218
        response => {
219
          console.log(`addRepository responded: ${response.id}, ${response.registeredBy}`);
220
          this.repo = response;
221
        },
222
        error => {
223
          console.log(error);
224
          this.loadingMessage = '';
225
          this.errorMessage = formErrorRegisterRepo;
226
        },
227
        () => {
228
          this.saveNewInterfaces();
229
          // TODO: update terms when backend is ready, maybe POST with updateRepository
230
        }
231
      );
232
    }
233
  }
234

    
235
  saveNewInterfaces() {
236
    if (this.repoInterfaces && (this.repoInterfaces.length > 0)) {
237
      from(this.repoInterfaces).pipe(
238
        concatMap(intrf => {
239
          if (intrf.id) {
240
            return this.repoService.updateInterface(this.repo.id, this.repo.registeredBy, intrf);
241
          } else {
242
            return this.repoService.addInterface(this.repo.datasourceType, this.repo.id, this.repo.registeredBy, intrf);
243
          }
244
        })
245
      ).subscribe(
246
        res => console.log('after save interfaces', JSON.stringify(res)),
247
        er => {
248
          console.log(er);
249
          this.loadingMessage = '';
250
          this.errorMessage = 'Not all changes were saved. Please try again';
251
        },
252
        () => {
253
          this.loadingMessage = '';
254
          this.repo = null;
255
          this.repoInterfaces = [];
256
          this.router.navigateByUrl(`/sources/register/${this.datasourceType}?step=finish`);
257
        }
258
      );
259
    }
260
  }
261
}
(6-6/10)