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