Support get functions in composition property modal
[sdc.git] / catalog-ui / src / app / ng2 / pages / properties-assignment / tosca-function / tosca-function.component.ts
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19
20 import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
21 import {ComponentMetadata, DataTypeModel, PropertyBEModel, PropertyModel} from 'app/models';
22 import {TopologyTemplateService} from "../../../services/component-services/topology-template.service";
23 import {WorkspaceService} from "../../workspace/workspace.service";
24 import {PropertiesService} from "../../../services/properties.service";
25 import {PROPERTY_DATA} from "../../../../utils/constants";
26 import {DataTypeService} from "../../../services/data-type.service";
27 import {ToscaGetFunctionType} from "../../../../models/tosca-get-function-type";
28 import {TranslateService} from "../../../shared/translator/translate.service";
29 import {ComponentGenericResponse} from '../../../services/responses/component-generic-response';
30 import {Observable} from 'rxjs/Observable';
31 import {PropertySource} from "../../../../models/property-source";
32 import {InstanceFeDetails} from "../../../../models/instance-fe-details";
33 import {ToscaGetFunction} from "../../../../models/tosca-get-function";
34 import {AbstractControl, FormControl, FormGroup, ValidationErrors, ValidatorFn} from "@angular/forms";
35
36 @Component({
37     selector: 'tosca-function',
38     templateUrl: './tosca-function.component.html',
39     styleUrls: ['./tosca-function.component.less'],
40 })
41 export class ToscaFunctionComponent implements OnInit {
42
43     @Input() property: PropertyBEModel;
44     @Input() componentInstanceMap: Map<string, InstanceFeDetails> = new Map<string, InstanceFeDetails>();
45     @Input() allowClear: boolean = true;
46     @Output() onValidFunction: EventEmitter<ToscaGetFunction> = new EventEmitter<ToscaGetFunction>();
47     @Output() onValidityChange: EventEmitter<boolean> = new EventEmitter<boolean>();
48
49     toscaGetFunctionValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
50         const toscaGetFunction: ToscaGetFunction = control.value;
51         const errors: ValidationErrors = {};
52         if (!toscaGetFunction.sourceName) {
53             errors.sourceName = { required: true };
54         }
55         if (!toscaGetFunction.functionType) {
56             errors.functionType = { required: true };
57         }
58         if (!toscaGetFunction.sourceUniqueId) {
59             errors.sourceUniqueId = { required: true };
60         }
61         if (!toscaGetFunction.sourceName) {
62             errors.sourceName = { required: true };
63         }
64         if (!toscaGetFunction.propertyPathFromSource) {
65             errors.propertyPathFromSource = { required: true };
66         }
67         if (!toscaGetFunction.propertyName) {
68             errors.propertyName = { required: true };
69         }
70         if (!toscaGetFunction.propertySource) {
71             errors.propertySource = { required: true };
72         }
73         return errors ? errors : null;
74     };
75
76     toscaGetFunctionForm: FormControl = new FormControl(new ToscaGetFunction(undefined), [this.toscaGetFunctionValidator]);
77     formGroup: FormGroup = new FormGroup({
78         'toscaGetFunction': this.toscaGetFunctionForm
79     });
80
81     TOSCA_FUNCTION_GET_PROPERTY = ToscaGetFunctionType.GET_PROPERTY;
82
83     selectedProperty: PropertyDropdownValue;
84     isLoading: boolean = false;
85     propertyDropdownList: Array<PropertyDropdownValue> = [];
86     toscaFunctions: Array<string> = [];
87     propertySourceList: Array<string> = [];
88     instanceNameAndIdMap: Map<string, string> = new Map<string, string>();
89     dropdownValuesLabel: string;
90     dropDownErrorMsg: string;
91     propertySource: string
92     toscaGetFunction: ToscaGetFunction = new ToscaGetFunction(undefined);
93
94     private componentMetadata: ComponentMetadata;
95
96     constructor(private topologyTemplateService: TopologyTemplateService,
97                 private workspaceService: WorkspaceService,
98                 private propertiesService: PropertiesService,
99                 private dataTypeService: DataTypeService,
100                 private translateService: TranslateService) {
101     }
102
103     ngOnInit(): void {
104         this.componentMetadata = this.workspaceService.metadata;
105         this.loadToscaFunctions();
106         this.loadPropertySourceDropdown();
107         this.initToscaGetFunction();
108         this.toscaGetFunctionForm.valueChanges.subscribe(toscaGetFunction => {
109             this.onValidityChange.emit(this.toscaGetFunctionForm.valid);
110             if (this.toscaGetFunctionForm.valid) {
111                 this.onValidFunction.emit(toscaGetFunction);
112             }
113         })
114     }
115
116     private initToscaGetFunction(): void {
117         if (!this.property.isToscaGetFunction()) {
118             return;
119         }
120         this.toscaGetFunction = new ToscaGetFunction(this.property.toscaGetFunction);
121         this.toscaGetFunctionForm.setValue(this.toscaGetFunction);
122         if (this.toscaGetFunction.functionType === ToscaGetFunctionType.GET_PROPERTY) {
123             if (this.toscaGetFunction.propertySource === PropertySource.SELF) {
124                 this.propertySource = PropertySource.SELF;
125             } else {
126                 this.propertySource = this.toscaGetFunction.sourceName;
127             }
128         }
129         if (this.toscaGetFunction.propertyName) {
130             this.loadPropertyDropdown(() => {
131                 this.selectedProperty = this.propertyDropdownList.find(property => property.propertyName === this.toscaGetFunction.propertyName)
132             });
133         }
134     }
135
136     private loadToscaFunctions(): void {
137         this.toscaFunctions.push(ToscaGetFunctionType.GET_INPUT);
138         this.toscaFunctions.push(ToscaGetFunctionType.GET_PROPERTY);
139     }
140
141     private loadPropertySourceDropdown(): void {
142         this.propertySourceList.push(PropertySource.SELF);
143         this.componentInstanceMap.forEach((value, key) => {
144             const instanceName = value.name;
145             this.instanceNameAndIdMap.set(instanceName, key);
146             if (instanceName !== PropertySource.SELF) {
147                 this.addToPropertySource(instanceName);
148             }
149         });
150     }
151
152     private addToPropertySource(source: string): void {
153         this.propertySourceList.push(source);
154         this.propertySourceList.sort((a, b) => {
155             if (a === PropertySource.SELF) {
156                 return -1;
157             } else if (b === PropertySource.SELF) {
158                 return 1;
159             }
160
161             return a.localeCompare(b);
162         });
163     }
164
165     onToscaFunctionChange(): void {
166         this.resetPropertySource();
167         if (this.isGetInputSelected()) {
168             this.setSelfPropertySource();
169             this.loadPropertyDropdown();
170         }
171     }
172
173     private loadPropertyDropdown(onComplete?: () => any): void  {
174         this.loadPropertyDropdownLabel();
175         this.loadPropertyDropdownValues(onComplete);
176     }
177
178     private resetForm(): void {
179         this.toscaGetFunction = new ToscaGetFunction(undefined);
180         this.toscaGetFunctionForm.setValue(new ToscaGetFunction(undefined));
181         this.propertySource = undefined;
182         this.selectedProperty = undefined;
183     }
184
185     private resetPropertySource(): void {
186         this.toscaGetFunction.propertyUniqueId = undefined;
187         this.toscaGetFunction.propertyName = undefined;
188         this.toscaGetFunction.propertySource = undefined;
189         this.toscaGetFunction.sourceUniqueId = undefined;
190         this.toscaGetFunction.sourceName = undefined;
191         this.toscaGetFunction.propertyPathFromSource = undefined;
192         this.propertySource = undefined;
193         this.selectedProperty = undefined;
194
195         const toscaGetFunction1 = new ToscaGetFunction(undefined);
196         toscaGetFunction1.functionType = this.toscaGetFunction.functionType;
197         this.toscaGetFunctionForm.setValue(toscaGetFunction1);
198     }
199
200     private loadPropertyDropdownLabel(): void {
201         if (!this.toscaGetFunction.functionType) {
202             return;
203         }
204         if (this.isGetInputSelected()) {
205             this.dropdownValuesLabel = this.translateService.translate('INPUT_DROPDOWN_LABEL');
206         } else if (this.isGetPropertySelected()) {
207             this.dropdownValuesLabel = this.translateService.translate('TOSCA_FUNCTION_PROPERTY_DROPDOWN_LABEL');
208         }
209     }
210
211     private loadPropertyDropdownValues(onComplete?: () => any): void {
212         if (!this.toscaGetFunction.functionType) {
213             return;
214         }
215         this.resetPropertyDropdown();
216         this.fillPropertyDropdownValues(onComplete);
217     }
218
219     private resetPropertyDropdown(): void {
220         this.dropDownErrorMsg = undefined;
221         this.selectedProperty = undefined;
222         this.propertyDropdownList = [];
223     }
224
225     private fillPropertyDropdownValues(onComplete?: () => any): void {
226         this.startLoading();
227         const propertiesObservable: Observable<ComponentGenericResponse> = this.getPropertyObservable();
228         propertiesObservable.subscribe( (response: ComponentGenericResponse) => {
229             const properties: PropertyBEModel[] = this.extractProperties(response);
230             if (!properties || properties.length === 0) {
231                 const msgCode = this.isGetInputSelected() ? 'TOSCA_FUNCTION_NO_INPUT_FOUND' : 'TOSCA_FUNCTION_NO_PROPERTY_FOUND';
232                 this.dropDownErrorMsg = this.translateService.translate(msgCode, {type: this.property.type});
233                 return;
234             }
235             this.addPropertiesToDropdown(properties);
236             if (this.propertyDropdownList.length == 0) {
237                 const msgCode = this.isGetInputSelected() ? 'TOSCA_FUNCTION_NO_INPUT_FOUND' : 'TOSCA_FUNCTION_NO_PROPERTY_FOUND';
238                 this.dropDownErrorMsg = this.translateService.translate(msgCode, {type: this.property.type});
239             }
240         }, (error) => {
241             console.error('An error occurred while loading properties.', error);
242         }, () => {
243             if (onComplete) {
244                 onComplete();
245             }
246             this.stopLoading();
247         });
248     }
249
250     private extractProperties(componentGenericResponse: ComponentGenericResponse): PropertyBEModel[] {
251         if (this.isGetInputSelected()) {
252             return componentGenericResponse.inputs;
253         }
254         if (this.isGetPropertySelected()) {
255             if (this.propertySource === PropertySource.SELF) {
256                 return componentGenericResponse.properties;
257             }
258             const componentInstanceProperties: PropertyModel[] = componentGenericResponse.componentInstancesProperties[this.instanceNameAndIdMap.get(this.propertySource)];
259             return this.removeSelectedProperty(componentInstanceProperties);
260         }
261     }
262
263     private getPropertyObservable(): Observable<ComponentGenericResponse> {
264         if (this.isGetInputSelected()) {
265             return this.topologyTemplateService.getComponentInputsValues(this.componentMetadata.componentType, this.componentMetadata.uniqueId);
266         }
267         if (this.isGetPropertySelected()) {
268             if (this.propertySource === PropertySource.SELF) {
269                 return this.topologyTemplateService.findAllComponentProperties(this.componentMetadata.componentType, this.componentMetadata.uniqueId);
270             }
271             return this.topologyTemplateService.getComponentInstanceProperties(this.componentMetadata.componentType, this.componentMetadata.uniqueId);
272         }
273     }
274
275     private removeSelectedProperty(componentInstanceProperties: PropertyModel[]): PropertyModel[] {
276         if (!componentInstanceProperties) {
277             return [];
278         }
279         return componentInstanceProperties.filter(property =>
280             (property.uniqueId !== this.property.uniqueId) ||
281             (property.uniqueId === this.property.uniqueId && property.resourceInstanceUniqueId !== this.property.parentUniqueId)
282         );
283     }
284
285     private addPropertyToDropdown(propertyDropdownValue: PropertyDropdownValue): void {
286         this.propertyDropdownList.push(propertyDropdownValue);
287         this.propertyDropdownList.sort((a, b) => a.propertyLabel.localeCompare(b.propertyLabel));
288     }
289
290     private addPropertiesToDropdown(properties: PropertyBEModel[]): void {
291         for (const property of properties) {
292             if (this.property.type === property.type) {
293                 this.addPropertyToDropdown({
294                     propertyName: property.name,
295                     propertyId: property.uniqueId,
296                     propertyLabel: property.name,
297                     propertyPath: [property.name]
298                 });
299             } else if (this.isComplexType(property.type)) {
300                 this.fillPropertyDropdownWithMatchingChildProperties(property);
301             }
302         }
303     }
304
305     private fillPropertyDropdownWithMatchingChildProperties(inputProperty: PropertyBEModel, parentPropertyList: Array<PropertyBEModel> = []): void {
306         const dataTypeFound: DataTypeModel = this.dataTypeService.getDataTypeByModelAndTypeName(this.componentMetadata.model, inputProperty.type);
307         if (!dataTypeFound || !dataTypeFound.properties) {
308             return;
309         }
310         parentPropertyList.push(inputProperty);
311         dataTypeFound.properties.forEach(dataTypeProperty => {
312             if (dataTypeProperty.type === this.property.type) {
313                 this.addPropertyToDropdown({
314                     propertyName: dataTypeProperty.name,
315                     propertyId: parentPropertyList[0].uniqueId,
316                     propertyLabel: parentPropertyList.map(property => property.name).join('->') + '->' + dataTypeProperty.name,
317                     propertyPath: [...parentPropertyList.map(property => property.name), dataTypeProperty.name]
318                 });
319             } else if (PROPERTY_DATA.SIMPLE_TYPES.indexOf(dataTypeProperty.type) === -1) {
320                 this.fillPropertyDropdownWithMatchingChildProperties(dataTypeProperty, [...parentPropertyList])
321             }
322         });
323     }
324
325     private isGetPropertySelected(): boolean {
326         return this.toscaGetFunction.functionType === ToscaGetFunctionType.GET_PROPERTY;
327     }
328
329     private isGetInputSelected(): boolean {
330         return this.toscaGetFunction.functionType === ToscaGetFunctionType.GET_INPUT;
331     }
332
333     private isComplexType(propertyType: string): boolean {
334         return PROPERTY_DATA.SIMPLE_TYPES.indexOf(propertyType) === -1;
335     }
336
337     private stopLoading(): void {
338         this.isLoading = false;
339     }
340
341     private startLoading(): void {
342         this.isLoading = true;
343     }
344
345     showDropdown(): boolean {
346         if (this.toscaGetFunction.functionType === ToscaGetFunctionType.GET_PROPERTY) {
347             return this.toscaGetFunction.propertySource && !this.isLoading && !this.dropDownErrorMsg;
348         }
349
350         return this.toscaGetFunction.functionType && !this.isLoading && !this.dropDownErrorMsg;
351     }
352
353     onPropertySourceChange(): void {
354         if (!this.toscaGetFunction.functionType || !this.propertySource) {
355             return;
356         }
357         this.toscaGetFunction.propertyUniqueId = undefined;
358         this.toscaGetFunction.propertyName = undefined;
359         this.toscaGetFunction.propertyPathFromSource = undefined;
360         if (this.propertySource === PropertySource.SELF) {
361             this.setSelfPropertySource();
362         } else {
363             this.toscaGetFunction.propertySource = PropertySource.INSTANCE;
364             this.toscaGetFunction.sourceName = this.propertySource;
365             this.toscaGetFunction.sourceUniqueId = this.instanceNameAndIdMap.get(this.propertySource);
366         }
367         this.toscaGetFunctionForm.setValue(this.toscaGetFunction);
368         this.loadPropertyDropdown();
369     }
370
371     private setSelfPropertySource(): void {
372         this.toscaGetFunction.propertySource = PropertySource.SELF;
373         this.toscaGetFunction.sourceName = this.componentMetadata.name;
374         this.toscaGetFunction.sourceUniqueId = this.componentMetadata.uniqueId;
375         this.toscaGetFunctionForm.setValue(this.toscaGetFunction);
376     }
377
378     onPropertyChange(): void {
379         this.toscaGetFunction.propertyUniqueId = this.selectedProperty.propertyId;
380         this.toscaGetFunction.propertyName = this.selectedProperty.propertyName;
381         this.toscaGetFunction.propertyPathFromSource = this.selectedProperty.propertyPath;
382         this.toscaGetFunctionForm.setValue(this.toscaGetFunction);
383     }
384
385     onClearValues() {
386         this.resetForm();
387     }
388
389     showClearButton(): boolean {
390         return this.allowClear && this.toscaGetFunction.functionType !== undefined;
391     }
392 }
393
394 export interface PropertyDropdownValue {
395     propertyName: string;
396     propertyId: string;
397     propertyLabel: string;
398     propertyPath: Array<string>;
399 }