Release version 1.13.7
[sdc.git] / catalog-ui / src / app / ng2 / components / logic / properties-table / dynamic-property / dynamic-property.component.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 import * as _ from "lodash";
22 import {Component, Input, Output, EventEmitter, ViewChild, ComponentRef} from "@angular/core";
23 import { PropertyFEModel, DerivedFEProperty, DerivedPropertyType } from "app/models";
24 import { PROPERTY_TYPES } from 'app/utils';
25 import { DataTypeService } from "../../../../services/data-type.service";
26 import { trigger, style, transition, animate } from '@angular/animations';
27 import {PropertiesUtils} from "../../../../pages/properties-assignment/services/properties.utils";
28 import {IUiElementChangeEvent} from "../../../ui/form-components/ui-element-base.component";
29 import {DynamicElementComponent} from "../../../ui/dynamic-element/dynamic-element.component";
30 import {SubPropertyToscaFunction} from "app/models/sub-property-tosca-function";
31
32 @Component({
33     selector: 'dynamic-property',
34     templateUrl: './dynamic-property.component.html',
35     styleUrls: ['./dynamic-property.component.less'],
36     animations: [trigger('fadeIn', [transition(':enter', [style({ opacity: '0' }), animate('.7s ease-out', style({ opacity: '1' }))])])]
37 })
38 export class DynamicPropertyComponent {
39
40     derivedPropertyTypes = DerivedPropertyType; //http://stackoverflow.com/questions/35835984/how-to-use-a-typescript-enum-value-in-an-angular2-ngswitch-statement
41     propType: DerivedPropertyType;
42     propPath: string;
43     isPropertyFEModel: boolean;
44     nestedLevel: number;
45     propertyTestsId: string;
46     constraints:string[];
47     checkboxDisabled: boolean = false;
48
49     @Input() canBeDeclared: boolean;
50     @Input() property: PropertyFEModel | DerivedFEProperty;
51     @Input() expandedChildId: string;
52     @Input() selectedPropertyId: string;
53     @Input() propertyNameSearchText: string;
54     @Input() readonly: boolean;
55     @Input() hasChildren: boolean;
56     @Input() hasDeclareOption:boolean;
57     @Input() disablePropertyValue: boolean;
58     @Input() hideCheckBox: boolean;
59     @Input() rootProperty: PropertyFEModel;
60
61     @Output('propertyChanged') emitter: EventEmitter<void> = new EventEmitter<void>();
62     @Output() expandChild: EventEmitter<string> = new EventEmitter<string>();
63     @Output() checkProperty: EventEmitter<string> = new EventEmitter<string>();
64     @Output() toggleTosca: EventEmitter<DerivedFEProperty> = new EventEmitter<DerivedFEProperty>();
65     @Output() deleteItem: EventEmitter<string> = new EventEmitter<string>();
66     @Output() clickOnPropertyRow: EventEmitter<PropertyFEModel | DerivedFEProperty> = new EventEmitter<PropertyFEModel | DerivedFEProperty>();
67     @Output() mapKeyChanged: EventEmitter<string> = new EventEmitter<string>();
68     @Output() addChildPropsToParent: EventEmitter<Array<DerivedFEProperty>> = new EventEmitter<Array<DerivedFEProperty>>();
69
70     @ViewChild('mapKeyInput') public mapKeyInput: DynamicElementComponent;
71
72     constructor(private propertiesUtils: PropertiesUtils, private dataTypeService: DataTypeService) {
73     }
74
75     ngOnInit() {
76         this.isPropertyFEModel = this.property instanceof PropertyFEModel;
77         this.propType = this.property.derivedDataType;
78         this.propPath = (this.property instanceof PropertyFEModel) ? this.property.name : this.property.propertiesName;
79         this.nestedLevel = (this.property.propertiesName.match(/#/g) || []).length;
80         this.rootProperty = (this.rootProperty) ? this.rootProperty : <PropertyFEModel>this.property;
81         this.propertyTestsId = this.getPropertyTestsId();
82
83         this.initConsraintsValues();
84     }
85
86     initConsraintsValues(){
87         let primitiveProperties = ['string', 'integer', 'float', 'boolean', PROPERTY_TYPES.TIMESTAMP];
88
89         //Property has constraints
90         if(this.property.constraints && this.property.constraints[0]){
91             this.constraints = this.property.constraints[0].validValues
92         }
93
94         //Complex Type
95         else if (primitiveProperties.indexOf(this.rootProperty.type) == -1 && primitiveProperties.indexOf(this.property.type) >= 0 ){
96             this.constraints = this.dataTypeService.getConstraintsByParentTypeAndUniqueID(this.rootProperty.type, this.property.name);           
97         }
98  
99         else{
100             this.constraints = null;
101         }
102         
103     }
104
105     ngDoCheck() {
106         // set custom error for mapKeyInput
107         if (this.mapKeyInput) {
108             const mapKeyInputControl = this.mapKeyInput.cmpRef.instance.control;
109             const mapKeyError = (<DerivedFEProperty>this.property).mapKeyError;
110             if (mapKeyInputControl.getError('mapKeyError') !== mapKeyError) {
111                 mapKeyInputControl.setErrors({mapKeyError});
112             }
113         }
114     }
115
116     ngOnChanges() {
117         this.propType = this.property.derivedDataType;
118         this.propPath = (this.property instanceof PropertyFEModel) ? this.property.name : this.property.propertiesName;
119         this.rootProperty = (this.rootProperty) ? this.rootProperty : <PropertyFEModel>this.property;
120         this.propertyTestsId = this.getPropertyTestsId();
121     }
122
123     onClickPropertyRow = (property, event) => {
124         // Because DynamicPropertyComponent is recrusive second time the event is fire event.stopPropagation = undefined
125         event && event.stopPropagation && event.stopPropagation();
126         this.clickOnPropertyRow.emit(property);
127     }
128
129     expandChildById = (id: string) => {
130         this.expandedChildId = id;
131         this.expandChild.emit(id);
132     }
133
134     checkedChange = (propName: string) => {
135         this.checkProperty.emit(propName);
136     }
137
138     toggleToscaFunction = (prop: DerivedFEProperty) => {
139         this.toggleTosca.emit(prop);
140     }
141
142     getHasChildren = (property:DerivedFEProperty): boolean => {// enter to this function only from base property (PropertyFEModel) and check for child property if it has children
143         return _.filter((<PropertyFEModel>this.property).flattenedChildren,(prop:DerivedFEProperty)=>{
144             return _.startsWith(prop.propertiesName + '#', property.propertiesName);
145         }).length > 1;
146     }
147
148     getPropertyTestsId = () => {
149         return [this.rootProperty.name].concat(this.rootProperty.getParentNamesArray(this.property.propertiesName, [], true)).join('.');
150     };
151
152     onElementChanged = (event: IUiElementChangeEvent) => {
153         this.property.updateValueObj(event.value, event.isValid);
154         if (this.property.hasValueObjChanged()) {
155             this.checkboxDisabled = true;
156         }
157         if (event.value === '' || event.value === null || event.value === undefined) {
158             this.checkboxDisabled = false;
159         }
160         this.emitter.emit();
161     };
162
163     createNewChildProperty = (): void => {
164
165         let parentToscaFunction = null;
166         if (this.property.type == PROPERTY_TYPES.MAP && this.property instanceof DerivedFEProperty && this.property.mapInlist) {
167             parentToscaFunction = this.property.toscaFunction;
168             this.property.toscaFunction = null;
169         }
170         let newProps: Array<DerivedFEProperty> = this.propertiesUtils.createListOrMapChildren(this.property, '', null);
171
172         this.propertiesUtils.assignFlattenedChildrenValues(this.property.valueObj, [newProps[0]], this.property.propertiesName);
173         if (this.property instanceof PropertyFEModel) {
174             this.addChildProps(newProps, this.property.name);
175         } else {
176             this.addChildPropsToParent.emit(newProps);
177         }
178         this.property.toscaFunction = parentToscaFunction;
179     }
180
181     addChildProps = (newProps: Array<DerivedFEProperty>, childPropName: string) => {
182
183         if (this.property instanceof PropertyFEModel) {
184             let insertIndex: number = this.property.getIndexOfChild(childPropName) + this.property.getCountOfChildren(childPropName); //insert after parent prop and existing children
185             this.property.flattenedChildren.splice(insertIndex, 0, ...newProps); //using ES6 spread operator
186             this.expandChildById(newProps[0].propertiesName);
187
188             this.updateMapKeyValueOnMainParent(newProps);
189         }
190     }
191
192     updateMapKeyValueOnMainParent(childrenProps: Array<DerivedFEProperty>){
193         if (this.property instanceof PropertyFEModel) {
194             const property: PropertyFEModel = <PropertyFEModel>this.property;
195             //Update only if all this property parents has key name
196             if (property.getParentNamesArray(childrenProps[0].propertiesName, []).indexOf('') === -1){
197                 angular.forEach(childrenProps, (prop:DerivedFEProperty):void => { //Update parent PropertyFEModel with value for each child, including nested props
198                     property.childPropUpdated(prop);
199                     if (prop.isChildOfListOrMap && prop.mapKey !== undefined) {
200                         property.childPropMapKeyUpdated(prop, prop.mapKey, true);
201                     }
202                 },this);
203                 //grab the cumulative value for the new item from parent PropertyFEModel and assign that value to DerivedFEProp[0] (which is the list or map parent with UUID of the set we just added)
204                 let parentNames = (<PropertyFEModel>property).getParentNamesArray(childrenProps[0].propertiesName, []);
205                 childrenProps[0].valueObj = _.get(property.valueObj, parentNames.join('.'), null);
206             }
207         }
208     }
209
210     childValueChanged = (property: DerivedFEProperty) => { //value of child property changed
211
212         if (this.property instanceof PropertyFEModel) { // will always be the case
213             if (this.property.getParentNamesArray(property.propertiesName, []).indexOf('') === -1) {//If one of the parents is empty key -don't save
214                 this.property.childPropUpdated(property);
215                 this.dataTypeService.checkForCustomBehavior(this.property);
216                 this.emitter.emit();
217             }
218         }
219     }
220
221     deleteListOrMapItem = (item: DerivedFEProperty) => {
222         if (this.property instanceof PropertyFEModel) {
223             const childMapKey = item.mapKey;
224             this.removeValueFromParent(item);
225             this.property.flattenedChildren.splice(this.property.getIndexOfChild(item.propertiesName), this.property.getCountOfChildren(item.propertiesName));
226             this.expandChildById(item.propertiesName);
227             if (this.property.type == PROPERTY_TYPES.LIST && this.property.schemaType == PROPERTY_TYPES.MAP && childMapKey != null) {
228                 let valueObject = JSON.parse(this.property.value);
229                 let innerObject = valueObject[item.parentMapKey];
230                 delete innerObject[childMapKey];
231                 this.property.valueObj = valueObject;
232                 this.property.value = JSON.stringify(valueObject);
233                 this.property.flattenedChildren[0].valueObj = valueObject;
234                 this.property.flattenedChildren[0].value = JSON.stringify(valueObject);
235                 this.property.flattenedChildren[0].valueObjIsChanged = true;
236             }
237         }
238     }
239
240     removeValueFromParent = (item: DerivedFEProperty) => {
241         if (this.property instanceof PropertyFEModel) {
242             let itemParent = (item.parentName == this.property.name)
243                 ? this.property : this.property.flattenedChildren.find(prop => prop.propertiesName == item.parentName);
244             if (!itemParent) {
245                 return;
246             }
247             let oldKey = item.getActualMapKey();
248             if (this.property.subPropertyToscaFunctions !== null) {
249                 let deletedIndex = item.toscaPath.length > 0 ? Number(item.toscaPath[item.toscaPath.length - 1]) : null;
250                 let parentIndex = item.toscaPath.length > 1 ? item.toscaPath.splice(0,item.toscaPath.length - 2) : null;
251                 let tempSubToscaFunction: SubPropertyToscaFunction[] = [];
252                 let toscaPathMap = new Map();
253                 this.property.subPropertyToscaFunctions.forEach((subToscaItem : SubPropertyToscaFunction) => {
254                     if ((subToscaItem.subPropertyPath.toString()).indexOf(item.toscaPath.toString()) == -1) {
255                         tempSubToscaFunction.push(subToscaItem);
256                     } else {
257                         if (item.derivedDataType == DerivedPropertyType.LIST ) {
258                             if (parentIndex != null) {
259                                 if ((subToscaItem.subPropertyPath.toString()).indexOf(parentIndex.toString()) != -1
260                                     && subToscaItem.subPropertyPath.length > parentIndex.length) {
261                                     let nextIndex = Number(subToscaItem.subPropertyPath[parentIndex.length]);
262                                     if(!isNaN(nextIndex) && !isNaN(deletedIndex) && nextIndex > deletedIndex) {
263                                         let revisedPAth = subToscaItem.subPropertyPath;
264                                         revisedPAth[parentIndex.length] = (nextIndex - 1).toString();
265                                         toscaPathMap.set(subToscaItem.subPropertyPath.toString(),revisedPAth.toString());
266                                     }
267                                 }
268                             } else {
269                                 if (subToscaItem.subPropertyPath.length == 1 && !isNaN(deletedIndex)) {
270                                     let nextElementIndex = Number(subToscaItem.subPropertyPath[0]);
271                                     if (!isNaN(nextElementIndex) && nextElementIndex > deletedIndex) {
272                                         subToscaItem.subPropertyPath[0] = (nextElementIndex - 1).toString();
273                                     }
274                                 }
275                             }
276                         }
277                     }
278                 });
279                 this.property.subPropertyToscaFunctions = tempSubToscaFunction;
280                 if (item.derivedDataType == DerivedPropertyType.LIST && parentIndex != null && toscaPathMap.size > 0) {
281                     this.property.flattenedChildren.forEach((childProperties : DerivedFEProperty) => {
282                         if (toscaPathMap.has(childProperties.toscaPath.toString())) {
283                             childProperties.toscaPath = toscaPathMap.get(childProperties.toscaPath.toString());
284                         }
285                     });
286                 }
287             }
288             if (item.derivedDataType == DerivedPropertyType.MAP && !item.mapInlist) {
289                 delete itemParent.valueObj[oldKey];
290                 if (itemParent instanceof PropertyFEModel) {
291                     delete itemParent.valueObjValidation[oldKey];
292                     itemParent.valueObjIsValid = itemParent.calculateValueObjIsValid();
293                 }
294                 this.property.childPropMapKeyUpdated(item, null);  // remove map key
295             } else {
296                 const itemIndex: number = this.property.flattenedChildren.filter(prop => prop.parentName == item.parentName).map(prop => prop.propertiesName).indexOf(item.propertiesName);
297                 itemParent.valueObj.splice(itemIndex, 1);
298                 if (itemParent instanceof PropertyFEModel) {
299                     itemParent.valueObjValidation.splice(itemIndex, 1);
300                     itemParent.valueObjIsValid = itemParent.calculateValueObjIsValid();
301                 }
302             }
303             if (itemParent instanceof PropertyFEModel) { //direct child
304                 this.emitter.emit();
305             } else { //nested child - need to update parent prop by getting flattened name (recurse through parents and replace map/list keys, etc)
306                 this.childValueChanged(itemParent);
307             }
308         }
309     }
310
311     updateChildKeyInParent(childProp: DerivedFEProperty, newMapKey: string) {
312         if (this.property instanceof PropertyFEModel) {
313             let oldKey = childProp.getActualMapKey();
314             let oldToscaPath = childProp.toscaPath;
315             this.property.childPropMapKeyUpdated(childProp, newMapKey);
316             this.updateChildMapKey(this.property.flattenedChildren, childProp.propertiesName, newMapKey);
317             if (this.property.subPropertyToscaFunctions != null) {
318                 this.property.subPropertyToscaFunctions.forEach((item : SubPropertyToscaFunction) => {
319                     if(item.subPropertyPath === oldToscaPath){
320                         item.subPropertyPath = childProp.toscaPath;
321                     }
322                 });
323             }
324             this.emitter.emit();
325         }
326     }
327
328     updateChildMapKey(childProps: Array<DerivedFEProperty>, parentName: string, newMapKey: string) {
329         childProps.forEach(tempDervObj => {
330             if (parentName === tempDervObj.parentName) {
331                 tempDervObj.mapKey = newMapKey;
332                 tempDervObj.toscaPath[tempDervObj.toscaPath.length - 2] = newMapKey;
333             }
334         });
335     }
336
337     preventInsertItem = (property:DerivedFEProperty):boolean => {
338         if(property.type == PROPERTY_TYPES.MAP && property.valueObj != null && Object.keys(property.valueObj).indexOf('') > -1 ){
339             return true;
340         }
341         return false;
342     }
343
344 }