Setting Tosca Function on top of unsaved value causes problems
[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() rootProperty: PropertyFEModel;
58
59     @Output('propertyChanged') emitter: EventEmitter<void> = new EventEmitter<void>();
60     @Output() expandChild: EventEmitter<string> = new EventEmitter<string>();
61     @Output() checkProperty: EventEmitter<string> = new EventEmitter<string>();
62     @Output() toggleTosca: EventEmitter<DerivedFEProperty> = new EventEmitter<DerivedFEProperty>();
63     @Output() deleteItem: EventEmitter<string> = new EventEmitter<string>();
64     @Output() clickOnPropertyRow: EventEmitter<PropertyFEModel | DerivedFEProperty> = new EventEmitter<PropertyFEModel | DerivedFEProperty>();
65     @Output() mapKeyChanged: EventEmitter<string> = new EventEmitter<string>();
66     @Output() addChildPropsToParent: EventEmitter<Array<DerivedFEProperty>> = new EventEmitter<Array<DerivedFEProperty>>();
67
68     @ViewChild('mapKeyInput') public mapKeyInput: DynamicElementComponent;
69
70     constructor(private propertiesUtils: PropertiesUtils, private dataTypeService: DataTypeService) {
71     }
72
73     ngOnInit() {
74         this.isPropertyFEModel = this.property instanceof PropertyFEModel;
75         this.propType = this.property.derivedDataType;
76         this.propPath = (this.property instanceof PropertyFEModel) ? this.property.name : this.property.propertiesName;
77         this.nestedLevel = (this.property.propertiesName.match(/#/g) || []).length;
78         this.rootProperty = (this.rootProperty) ? this.rootProperty : <PropertyFEModel>this.property;
79         this.propertyTestsId = this.getPropertyTestsId();
80
81         this.initConsraintsValues();
82     }
83
84     initConsraintsValues(){
85         let primitiveProperties = ['string', 'integer', 'float', 'boolean', PROPERTY_TYPES.TIMESTAMP];
86
87         //Property has constraints
88         if(this.property.constraints && this.property.constraints[0]){
89             this.constraints = this.property.constraints[0].validValues
90         }
91
92         //Complex Type
93         else if (primitiveProperties.indexOf(this.rootProperty.type) == -1 && primitiveProperties.indexOf(this.property.type) >= 0 ){
94             this.constraints = this.dataTypeService.getConstraintsByParentTypeAndUniqueID(this.rootProperty.type, this.property.name);           
95         }
96  
97         else{
98             this.constraints = null;
99         }
100         
101     }
102
103     ngDoCheck() {
104         // set custom error for mapKeyInput
105         if (this.mapKeyInput) {
106             const mapKeyInputControl = this.mapKeyInput.cmpRef.instance.control;
107             const mapKeyError = (<DerivedFEProperty>this.property).mapKeyError;
108             if (mapKeyInputControl.getError('mapKeyError') !== mapKeyError) {
109                 mapKeyInputControl.setErrors({mapKeyError});
110             }
111         }
112     }
113
114     ngOnChanges() {
115         this.propType = this.property.derivedDataType;
116         this.propPath = (this.property instanceof PropertyFEModel) ? this.property.name : this.property.propertiesName;
117         this.rootProperty = (this.rootProperty) ? this.rootProperty : <PropertyFEModel>this.property;
118         this.propertyTestsId = this.getPropertyTestsId();
119     }
120
121     onClickPropertyRow = (property, event) => {
122         // Because DynamicPropertyComponent is recrusive second time the event is fire event.stopPropagation = undefined
123         event && event.stopPropagation && event.stopPropagation();
124         this.clickOnPropertyRow.emit(property);
125     }
126
127     expandChildById = (id: string) => {
128         this.expandedChildId = id;
129         this.expandChild.emit(id);
130     }
131
132     checkedChange = (propName: string) => {
133         this.checkProperty.emit(propName);
134     }
135
136     toggleToscaFunction = (prop: DerivedFEProperty) => {
137         this.toggleTosca.emit(prop);
138     }
139
140     getHasChildren = (property:DerivedFEProperty): boolean => {// enter to this function only from base property (PropertyFEModel) and check for child property if it has children
141         return _.filter((<PropertyFEModel>this.property).flattenedChildren,(prop:DerivedFEProperty)=>{
142             return _.startsWith(prop.propertiesName + '#', property.propertiesName);
143         }).length > 1;
144     }
145
146     getPropertyTestsId = () => {
147         return [this.rootProperty.name].concat(this.rootProperty.getParentNamesArray(this.property.propertiesName, [], true)).join('.');
148     };
149
150     onElementChanged = (event: IUiElementChangeEvent) => {
151         this.property.updateValueObj(event.value, event.isValid);
152         if (this.property.hasValueObjChanged()) {
153             this.checkboxDisabled = true;
154         }
155         if (event.value === '' || event.value === null || event.value === undefined) {
156             this.checkboxDisabled = false;
157         }
158         this.emitter.emit();
159     };
160
161     createNewChildProperty = (): void => {
162
163         let mapKeyValue = this.property instanceof DerivedFEProperty ? this.property.mapKey : "";
164         let parentToscaFunction = null;
165         if (this.property.type == PROPERTY_TYPES.LIST && mapKeyValue === "") {
166             if (this.property.value != null) {
167                 const valueJson = JSON.parse(this.property.value);
168                 if (this.property instanceof PropertyFEModel && this.property.expandedChildPropertyId != null) {
169                     let indexNumber = Number(Object.keys(valueJson).sort().reverse()[0]) + 1;
170                     mapKeyValue = indexNumber.toString();
171                 }else{
172                     mapKeyValue = Object.keys(valueJson).sort().reverse()[0];
173                 }
174             }else {
175                 mapKeyValue = "0";
176             }
177         }
178         if (this.property.type == PROPERTY_TYPES.MAP && this.property instanceof DerivedFEProperty && this.property.mapInlist) {
179             parentToscaFunction = this.property.toscaFunction;
180             this.property.toscaFunction = null;
181         }
182         let newProps: Array<DerivedFEProperty> = this.propertiesUtils.createListOrMapChildren(this.property, mapKeyValue, null);
183
184         this.propertiesUtils.assignFlattenedChildrenValues(this.property.valueObj, [newProps[0]], this.property.propertiesName);
185         if (this.property instanceof PropertyFEModel) {
186             this.addChildProps(newProps, this.property.name);
187         } else {
188             this.addChildPropsToParent.emit(newProps);
189         }
190         this.property.toscaFunction = parentToscaFunction;
191     }
192
193     addChildProps = (newProps: Array<DerivedFEProperty>, childPropName: string) => {
194
195         if (this.property instanceof PropertyFEModel) {
196             let insertIndex: number = this.property.getIndexOfChild(childPropName) + this.property.getCountOfChildren(childPropName); //insert after parent prop and existing children
197             this.property.flattenedChildren.splice(insertIndex, 0, ...newProps); //using ES6 spread operator
198             this.expandChildById(newProps[0].propertiesName);
199
200             this.updateMapKeyValueOnMainParent(newProps);
201         }
202     }
203
204     updateMapKeyValueOnMainParent(childrenProps: Array<DerivedFEProperty>){
205         if (this.property instanceof PropertyFEModel) {
206             const property: PropertyFEModel = <PropertyFEModel>this.property;
207             //Update only if all this property parents has key name
208             if (property.getParentNamesArray(childrenProps[0].propertiesName, []).indexOf('') === -1){
209                 angular.forEach(childrenProps, (prop:DerivedFEProperty):void => { //Update parent PropertyFEModel with value for each child, including nested props
210                     property.childPropUpdated(prop);
211                     if (prop.isChildOfListOrMap && prop.mapKey !== undefined) {
212                         property.childPropMapKeyUpdated(prop, prop.mapKey, true);
213                     }
214                 },this);
215                 //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)
216                 let parentNames = (<PropertyFEModel>property).getParentNamesArray(childrenProps[0].propertiesName, []);
217                 childrenProps[0].valueObj = _.get(property.valueObj, parentNames.join('.'), null);
218             }
219         }
220     }
221
222     childValueChanged = (property: DerivedFEProperty) => { //value of child property changed
223
224         if (this.property instanceof PropertyFEModel) { // will always be the case
225             if (this.property.getParentNamesArray(property.propertiesName, []).indexOf('') === -1) {//If one of the parents is empty key -don't save
226                 this.property.childPropUpdated(property);
227                 this.dataTypeService.checkForCustomBehavior(this.property);
228                 this.emitter.emit();
229             }
230         }
231     }
232
233     deleteListOrMapItem = (item: DerivedFEProperty) => {
234         if (this.property instanceof PropertyFEModel) {
235             const childMapKey = item.mapKey;
236             this.removeValueFromParent(item);
237             this.property.flattenedChildren.splice(this.property.getIndexOfChild(item.propertiesName), this.property.getCountOfChildren(item.propertiesName));
238             this.expandChildById(item.propertiesName);
239             if (this.property.type == PROPERTY_TYPES.LIST && this.property.schemaType == PROPERTY_TYPES.MAP && childMapKey != null) {
240                 let valueObject = JSON.parse(this.property.value);
241                 let innerObject = valueObject[item.parentMapKey];
242                 delete innerObject[childMapKey];
243                 this.property.valueObj = valueObject;
244                 this.property.value = JSON.stringify(valueObject);
245                 this.property.flattenedChildren[0].valueObj = valueObject;
246                 this.property.flattenedChildren[0].value = JSON.stringify(valueObject);
247                 this.property.flattenedChildren[0].valueObjIsChanged = true;
248             }
249         }
250     }
251
252     removeValueFromParent = (item: DerivedFEProperty) => {
253         if (this.property instanceof PropertyFEModel) {
254             let itemParent = (item.parentName == this.property.name)
255                 ? this.property : this.property.flattenedChildren.find(prop => prop.propertiesName == item.parentName);
256             if (!itemParent) {
257                 return;
258             }
259             let oldKey = item.getActualMapKey();
260             let keyIndex : number = 0;
261                 if(item.parentMapKey != null && oldKey != null) {
262                     keyIndex = 1;
263                 }
264                 if(item.parentMapKey != null && oldKey == null) {
265                     oldKey = item.parentMapKey;
266                 }
267             if (this.property.subPropertyToscaFunctions !== null) {
268                 let tempSubToscaFunction: SubPropertyToscaFunction[] = [];
269                 this.property.subPropertyToscaFunctions.forEach((subToscaItem : SubPropertyToscaFunction) => {
270                     if(subToscaItem.subPropertyPath[keyIndex] != oldKey){
271                         tempSubToscaFunction.push(subToscaItem);
272                     }
273                 });
274                 this.property.subPropertyToscaFunctions = tempSubToscaFunction;
275             }
276             if (item.derivedDataType == DerivedPropertyType.MAP && !item.mapInlist) {
277                 delete itemParent.valueObj[oldKey];
278                 if (itemParent instanceof PropertyFEModel) {
279                     delete itemParent.valueObjValidation[oldKey];
280                     itemParent.valueObjIsValid = itemParent.calculateValueObjIsValid();
281                 }
282                 this.property.childPropMapKeyUpdated(item, null);  // remove map key
283             } else {
284                 const itemIndex: number = this.property.flattenedChildren.filter(prop => prop.parentName == item.parentName).map(prop => prop.propertiesName).indexOf(item.propertiesName);
285                 itemParent.valueObj.splice(itemIndex, 1);
286                 if (itemParent instanceof PropertyFEModel) {
287                     itemParent.valueObjValidation.splice(itemIndex, 1);
288                     itemParent.valueObjIsValid = itemParent.calculateValueObjIsValid();
289                 }
290             }
291             if (itemParent instanceof PropertyFEModel) { //direct child
292                 this.emitter.emit();
293             } else { //nested child - need to update parent prop by getting flattened name (recurse through parents and replace map/list keys, etc)
294                 this.childValueChanged(itemParent);
295             }
296         }
297     }
298
299     updateChildKeyInParent(childProp: DerivedFEProperty, newMapKey: string) {
300         if (this.property instanceof PropertyFEModel) {
301             let oldKey = childProp.getActualMapKey();
302             this.property.childPropMapKeyUpdated(childProp, newMapKey);
303             this.property.flattenedChildren.forEach(tempDervObj => {
304                 if (childProp.propertiesName === tempDervObj.parentName) {
305                     tempDervObj.mapKey = newMapKey;
306                 }
307             });
308             if (this.property.subPropertyToscaFunctions != null) {
309                 this.property.subPropertyToscaFunctions.forEach((item : SubPropertyToscaFunction) => {
310                     if(item.subPropertyPath[0] === oldKey){
311                         item.subPropertyPath = [newMapKey];
312                     }
313                 });
314             }
315             this.emitter.emit();
316         }
317     }
318
319     preventInsertItem = (property:DerivedFEProperty):boolean => {
320         if(property.type == PROPERTY_TYPES.MAP && property.valueObj != null && Object.keys(property.valueObj).indexOf('') > -1 ){
321             return true;
322         }
323         return false;
324     }
325
326 }