753cb6afe051ca07c5da4b3760467407750a2cb1
[sdc.git] / catalog-ui / src / app / ng2 / pages / properties-assignment / services / properties.utils.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 { Injectable } from '@angular/core';
23 import { DataTypeModel, PropertyFEModel, PropertyBEModel, InstanceBePropertiesMap, InstanceFePropertiesMap, DerivedFEProperty,  DerivedPropertyType, InputFEModel} from "app/models";
24 import { DataTypeService } from "app/ng2/services/data-type.service";
25 import { PropertiesService } from "app/ng2/services/properties.service";
26 import { PROPERTY_TYPES, PROPERTY_DATA } from "app/utils";
27 import { SubPropertyToscaFunction } from "app/models/sub-property-tosca-function";
28
29 @Injectable()
30 export class PropertiesUtils {
31
32     constructor(private dataTypeService:DataTypeService, private propertiesService: PropertiesService) {}
33
34     /**
35      * Entry point when getting properties from server
36      * For each instance, loop through each property, and:
37      * 1. Create flattened children
38      * 2. Check against inputs to see if any props are declared and disable them
39      * 3. Initialize valueObj (which also creates any new list/map flattened children as needed)
40      * Returns InstanceFePropertiesMap
41      */
42     public convertPropertiesMapToFEAndCreateChildren = (instancePropertiesMap:InstanceBePropertiesMap, isVF:boolean, inputs?:Array<InputFEModel>, model?:string): InstanceFePropertiesMap => {
43         let instanceFePropertiesMap:InstanceFePropertiesMap = new InstanceFePropertiesMap();
44         angular.forEach(instancePropertiesMap, (properties:Array<PropertyBEModel>, instanceId:string) => {
45             let propertyFeArray: Array<PropertyFEModel> = [];
46             _.forEach(properties, (property: PropertyBEModel) => {
47         
48                 if (this.dataTypeService.getDataTypeByModelAndTypeName(model, property.type)) { // if type not exist in data types remove property from list
49
50                     let newFEProp: PropertyFEModel = new PropertyFEModel(property); //Convert property to FE
51                     if (!newFEProp.parentUniqueId) {
52                         newFEProp.parentUniqueId = instanceId;
53                     }
54                     this.initValueObjectRef(newFEProp); //initialize valueObj AND creates flattened children
55                     propertyFeArray.push(newFEProp);
56                     newFEProp.updateExpandedChildPropertyId(newFEProp.name); //display only the first level of children
57                     this.dataTypeService.checkForCustomBehavior(newFEProp);
58
59                     if (newFEProp.isToscaFunction()) {
60                         return;
61                     }
62                     //if this prop (or any children) are declared, set isDeclared and disable checkbox on parents/children
63                     if (newFEProp.getInputValues && newFEProp.getInputValues.length) {
64                         newFEProp.getInputValues.forEach(propInputDetail => {
65                             let inputPath = propInputDetail.inputPath;
66                             if (!inputPath) { //TODO: this is a workaround until Marina adds inputPath
67                                 let input = inputs.find(input => input.uniqueId == propInputDetail.inputId);
68                                 if (!input) { console.log("CANNOT FIND INPUT FOR " + propInputDetail.inputId); return; }
69                                 else inputPath = input.inputPath;
70                             }
71                             if (inputPath == newFEProp.name) inputPath = undefined; // if not complex we need to remove the inputPath from FEModel so we not look for a child
72                             newFEProp.setAsDeclared(inputPath); //if a path is sent, its a child prop. this param is optional
73                             this.propertiesService.disableRelatedProperties(newFEProp, inputPath);
74                         });
75                     }
76                     if (newFEProp.getPolicyValues && newFEProp.getPolicyValues.length) {
77                         newFEProp.setAsDeclared(newFEProp.inputPath); //if a path is sent, its a child prop. this param is optional
78                         this.propertiesService.disableRelatedProperties(newFEProp, newFEProp.inputPath);
79                     }
80                 }
81             });
82             instanceFePropertiesMap[instanceId] = propertyFeArray;
83
84         });
85         return instanceFePropertiesMap;
86     }
87
88     public convertAddPropertyBAToPropertyFE = (property: PropertyBEModel): PropertyFEModel => {
89         const newFEProp: PropertyFEModel = new PropertyFEModel(property); //Convert property to FE
90         this.initValueObjectRef(newFEProp);
91         newFEProp.updateExpandedChildPropertyId(newFEProp.name); //display only the first level of children
92         this.dataTypeService.checkForCustomBehavior(newFEProp);
93         return newFEProp;
94     }
95
96     public createListOrMapChildren = (property:PropertyFEModel | DerivedFEProperty, key: string, valueObj: any): Array<DerivedFEProperty> => {
97         let newProps: Array<DerivedFEProperty> = [];
98         let parentProp = new DerivedFEProperty(property, property.propertiesName, true, key, valueObj);
99         newProps.push(parentProp);
100
101         if (!property.schema.property.isSimpleType) {
102             let additionalChildren:Array<DerivedFEProperty> = this.createFlattenedChildren(property.schema.property.type, parentProp.propertiesName);
103             this.assignFlattenedChildrenValues(parentProp.valueObj, additionalChildren, parentProp.propertiesName);
104             additionalChildren.forEach(prop => prop.canBeDeclared = false);
105             newProps.push(...additionalChildren);
106         }
107         return newProps;
108     }
109
110     /**
111      * Creates derivedFEProperties of a specified type and returns them.
112      */
113     private createFlattenedChildren = (type: string, parentName: string):Array<DerivedFEProperty> => {
114         let tempProps: Array<DerivedFEProperty> = [];
115         let dataTypeObj: DataTypeModel = this.dataTypeService.getDataTypeByTypeName(type);
116         this.dataTypeService.getDerivedDataTypeProperties(dataTypeObj, tempProps, parentName);
117         return _.sortBy(tempProps, ['propertiesName']);
118     }
119
120     /* Sets the valueObj of parent property and its children.
121     * Note: This logic is different than assignflattenedchildrenvalues - here we merge values, there we pick either the parents value, props value, or default value - without merging.
122     */
123     public initValueObjectRef = (property: PropertyFEModel): void => {
124         property.resetValueObjValidation();
125         if (property.isDeclared) { //if property is declared, it gets a simple input instead. List and map values and pseudo-children will be handled in property component
126             property.valueObj = property.value || property.defaultValue || null;  // use null for empty value object
127             if (property.valueObj && typeof property.valueObj == 'object') {
128                 property.valueObj = JSON.stringify(property.valueObj);
129             }
130         } else {
131             property.valueObj = property.getValueObj();
132             if (property.derivedDataType == DerivedPropertyType.LIST || property.derivedDataType == DerivedPropertyType.MAP) {
133                 property.flattenedChildren = [];
134                 Object.keys(property.valueObj).forEach((key) => {
135                     property.flattenedChildren.push(...this.createListOrMapChildren(property, key, property.valueObj[key]));
136                     const lastCreatedChild = property.flattenedChildren.slice(-1)[0];
137                     if (property.schemaType == PROPERTY_TYPES.MAP && property.valueObj[key]){
138                         const nestedValue:object = property.valueObj[key];
139                         Object.keys(nestedValue).forEach((keyNested) => {
140                             property.flattenedChildren.push(...this.createListOrMapChildren(lastCreatedChild, keyNested, nestedValue[keyNested]));
141                         });
142                     };
143                 });
144             } else if (property.derivedDataType === DerivedPropertyType.COMPLEX) {
145                 property.flattenedChildren = this.createFlattenedChildren(property.type, property.name);
146                 this.assignFlattenedChildrenValues(property.valueObj, property.flattenedChildren, property.name);
147                 this.setFlattenedChildernToscaFunction(property.subPropertyToscaFunctions, property.flattenedChildren, property.name);
148                 property.flattenedChildren.forEach((childProp) => {
149                     property.childPropUpdated(childProp);
150                 });
151
152             }
153         }
154         property.updateValueObjOrig();
155     };
156
157     public setFlattenedChildernToscaFunction = (subPropertyToscaFunctions: SubPropertyToscaFunction[], derivedPropArray: Array<DerivedFEProperty>, topLevelPropertyName: string) => {
158         if (!subPropertyToscaFunctions || !derivedPropArray || !topLevelPropertyName){
159             return;
160         }
161         derivedPropArray.forEach((prop, index) => {
162             const subPropertyPath = prop.propertiesName.substring(prop.propertiesName.indexOf(topLevelPropertyName) + topLevelPropertyName.length + 1);
163             subPropertyToscaFunctions.forEach(subPropertyToscaFunction => {
164                 const toscaFunctionPath = subPropertyToscaFunction.subPropertyPath.join('#');
165                 if (subPropertyPath === toscaFunctionPath){
166                     prop.toscaFunction = subPropertyToscaFunction.toscaFunction;
167                 }
168             })
169         })
170     }
171
172     /*
173     * Loops through flattened properties array and to assign values
174     * Then, convert any neccessary strings to objects, and vis-versa
175     * For list or map property, creates new children props if valueObj has values
176     */
177     public assignFlattenedChildrenValues = (parentValueJSON: any, derivedPropArray: Array<DerivedFEProperty>, parentName: string) => {
178         if (!derivedPropArray || !parentName) return;
179         let propsToPushMap: Map<number, Array<DerivedFEProperty>> = new Map<number, Array<DerivedFEProperty>>();
180         derivedPropArray.forEach((prop, index) => {
181
182             let propNameInObj = prop.propertiesName.substring(prop.propertiesName.indexOf(parentName) + parentName.length + 1).split('#').join('.'); //extract everything after parent name
183             prop.valueObj = _.get(parentValueJSON, propNameInObj, prop.value || prop.defaultValue || null); //assign value -first value of parent if exists. If not, prop.value if not, prop.defaultvalue
184             prop.value = (prop.valueObj !== null && (typeof prop.valueObj) != 'string') ? JSON.stringify(prop.valueObj) : prop.valueObj;
185
186             if ((prop.isDeclared || prop.type == PROPERTY_TYPES.STRING || prop.type == PROPERTY_TYPES.JSON)) { //Stringify objects of items that are declared or from type string/json
187                 prop.valueObj = (prop.valueObj !== null && typeof prop.valueObj == 'object') ? JSON.stringify(prop.valueObj) : prop.valueObj;
188             } else if(prop.type == PROPERTY_TYPES.INTEGER || prop.type == PROPERTY_TYPES.FLOAT || prop.type == PROPERTY_TYPES.BOOLEAN){ //parse ints and non-string simple types
189                 prop.valueObj = (prop.valueObj !== null && typeof prop.valueObj == PROPERTY_TYPES.STRING) ? JSON.parse(prop.valueObj) : prop.valueObj;
190             } else { //parse strings that should be objects
191                 if (prop.derivedDataType == DerivedPropertyType.COMPLEX) {
192                     prop.valueObj = (prop.valueObj === null || typeof prop.valueObj != 'object') ? JSON.parse(prop.valueObj || '{}') : prop.valueObj;
193                 } else if (prop.derivedDataType == DerivedPropertyType.LIST) {
194                     prop.valueObj = (prop.valueObj === null || typeof prop.valueObj != 'object') ? JSON.parse(prop.valueObj || '[]') : prop.valueObj;
195                 } else if (prop.derivedDataType == DerivedPropertyType.MAP) {
196                     if (!prop.isChildOfListOrMap || !prop.schema.property.isSimpleType) {
197                         prop.valueObj = (prop.valueObj === null || typeof prop.valueObj != 'object') ? JSON.parse(prop.valueObj || '{}') : prop.valueObj;
198                     }
199                 }
200                 if ((prop.derivedDataType == DerivedPropertyType.LIST || prop.derivedDataType == DerivedPropertyType.MAP) && typeof prop.valueObj == 'object' && prop.valueObj !== null && Object.keys(prop.valueObj).length) {
201                     let newProps: Array<DerivedFEProperty> = [];
202                     Object.keys(prop.valueObj).forEach((key) => {
203                         newProps.push(...this.createListOrMapChildren(prop, key, prop.valueObj[key]));//create new children, assign their values, and then add to array
204                     });
205                     propsToPushMap[index + 1] = newProps;
206                 }
207             }
208
209             prop.valueObj = PropertyFEModel.cleanValueObj(prop.valueObj);
210         });
211
212         //add props after we're done looping (otherwise our loop gets messed up). Push in reverse order, so we dont mess up indexes.
213         Object.keys(propsToPushMap).reverse().forEach((indexToInsert) => {
214             derivedPropArray.splice(+indexToInsert, 0, ...propsToPushMap[indexToInsert]); //slacker parsing
215         });
216     }
217
218     public resetPropertyValue = (property: PropertyFEModel, newValue: string, nestedPath?: string): void => {
219         property.value = newValue;
220         if (nestedPath) {
221             let newProp = property.flattenedChildren.find(prop => prop.propertiesName == nestedPath);
222             newProp && this.assignFlattenedChildrenValues(JSON.parse(newValue), [newProp], property.name);
223             property.updateValueObjOrig();
224         } else {
225             this.initValueObjectRef(property);
226         }
227     }
228
229 }