Fix changing property in node filter issue
[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, state, 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
31 @Component({
32     selector: 'dynamic-property',
33     templateUrl: './dynamic-property.component.html',
34     styleUrls: ['./dynamic-property.component.less'],
35     animations: [trigger('fadeIn', [transition(':enter', [style({ opacity: '0' }), animate('.7s ease-out', style({ opacity: '1' }))])])]
36 })
37 export class DynamicPropertyComponent {
38
39     derivedPropertyTypes = DerivedPropertyType; //http://stackoverflow.com/questions/35835984/how-to-use-a-typescript-enum-value-in-an-angular2-ngswitch-statement
40     propType: DerivedPropertyType;
41     propPath: string;
42     isPropertyFEModel: boolean;
43     nestedLevel: number;
44     propertyTestsId: string;
45     constraints:string[];
46
47     @Input() canBeDeclared: boolean;
48     @Input() property: PropertyFEModel | DerivedFEProperty;
49     @Input() expandedChildId: string;
50     @Input() selectedPropertyId: string;
51     @Input() propertyNameSearchText: string;
52     @Input() readonly: boolean;
53     @Input() hasChildren: boolean;
54     @Input() hasDeclareOption:boolean;
55     @Input() rootProperty: PropertyFEModel;
56
57     @Output('propertyChanged') emitter: EventEmitter<void> = new EventEmitter<void>();
58     @Output() expandChild: EventEmitter<string> = new EventEmitter<string>();
59     @Output() checkProperty: EventEmitter<string> = new EventEmitter<string>();
60     @Output() deleteItem: EventEmitter<string> = new EventEmitter<string>();
61     @Output() clickOnPropertyRow: EventEmitter<PropertyFEModel | DerivedFEProperty> = new EventEmitter<PropertyFEModel | DerivedFEProperty>();
62     @Output() mapKeyChanged: EventEmitter<string> = new EventEmitter<string>();
63     @Output() addChildPropsToParent: EventEmitter<Array<DerivedFEProperty>> = new EventEmitter<Array<DerivedFEProperty>>();
64
65     @ViewChild('mapKeyInput') public mapKeyInput: DynamicElementComponent;
66
67     constructor(private propertiesUtils: PropertiesUtils, private dataTypeService: DataTypeService) {
68     }
69
70     ngOnInit() {
71         this.isPropertyFEModel = this.property instanceof PropertyFEModel;
72         this.propType = this.property.derivedDataType;
73         this.propPath = (this.property instanceof PropertyFEModel) ? this.property.name : this.property.propertiesName;
74         this.nestedLevel = (this.property.propertiesName.match(/#/g) || []).length;
75         this.rootProperty = (this.rootProperty) ? this.rootProperty : <PropertyFEModel>this.property;
76         this.propertyTestsId = this.getPropertyTestsId();
77
78         this.initConsraintsValues();
79     }
80
81     initConsraintsValues(){
82         let primitiveProperties = ['string', 'integer', 'float', 'boolean', PROPERTY_TYPES.TIMESTAMP];
83
84         //Property has constraints
85         if(this.property.constraints && this.property.constraints[0]){
86             this.constraints = this.property.constraints[0].validValues
87         }
88
89         //Complex Type
90         else if (primitiveProperties.indexOf(this.rootProperty.type) == -1 && primitiveProperties.indexOf(this.property.type) >= 0 ){
91             this.constraints = this.dataTypeService.getConstraintsByParentTypeAndUniqueID(this.rootProperty.type, this.property.name);           
92         }
93  
94         else{
95             this.constraints = null;
96         }
97         
98     }
99
100     ngDoCheck() {
101         // set custom error for mapKeyInput
102         if (this.mapKeyInput) {
103             const mapKeyInputControl = this.mapKeyInput.cmpRef.instance.control;
104             const mapKeyError = (<DerivedFEProperty>this.property).mapKeyError;
105             if (mapKeyInputControl.getError('mapKeyError') !== mapKeyError) {
106                 mapKeyInputControl.setErrors({mapKeyError});
107             }
108         }
109     }
110
111     ngOnChanges() {
112         this.propType = this.property.derivedDataType;
113         this.propPath = (this.property instanceof PropertyFEModel) ? this.property.name : this.property.propertiesName;
114         this.propertyTestsId = this.getPropertyTestsId(); 
115     }
116
117
118     onClickPropertyRow = (property, event) => {
119         // Because DynamicPropertyComponent is recrusive second time the event is fire event.stopPropagation = undefined
120         event && event.stopPropagation && event.stopPropagation();
121         this.clickOnPropertyRow.emit(property);
122     }
123
124
125     expandChildById = (id: string) => {
126         this.expandedChildId = id;
127         this.expandChild.emit(id);
128     }
129
130     checkedChange = (propName: string) => {
131         this.checkProperty.emit(propName);
132     }
133
134     getHasChildren = (property:DerivedFEProperty): boolean => {// enter to this function only from base property (PropertyFEModel) and check for child property if it has children
135         return _.filter((<PropertyFEModel>this.property).flattenedChildren,(prop:DerivedFEProperty)=>{
136             return _.startsWith(prop.propertiesName + '#', property.propertiesName);
137         }).length > 1;
138     }
139
140     getPropertyTestsId = () => {
141         return [this.rootProperty.name].concat(this.rootProperty.getParentNamesArray(this.property.propertiesName, [], true)).join('.');
142     };
143
144     onElementChanged = (event: IUiElementChangeEvent) => {
145         this.property.updateValueObj(event.value, event.isValid);
146         this.emitter.emit();
147     };
148
149     createNewChildProperty = (): void => {
150        
151         let newProps: Array<DerivedFEProperty> = this.propertiesUtils.createListOrMapChildren(this.property, "", null);
152
153         this.propertiesUtils.assignFlattenedChildrenValues(this.property.valueObj, [newProps[0]], this.property.propertiesName);
154         if (this.property instanceof PropertyFEModel) {
155             this.addChildProps(newProps, this.property.name);
156         } else {
157             this.addChildPropsToParent.emit(newProps);
158         }
159     }
160
161     addChildProps = (newProps: Array<DerivedFEProperty>, childPropName: string) => {
162
163         if (this.property instanceof PropertyFEModel) {
164             let insertIndex: number = this.property.getIndexOfChild(childPropName) + this.property.getCountOfChildren(childPropName); //insert after parent prop and existing children
165             this.property.flattenedChildren.splice(insertIndex, 0, ...newProps); //using ES6 spread operator
166             this.expandChildById(newProps[0].propertiesName);
167
168             this.updateMapKeyValueOnMainParent(newProps);
169             this.emitter.emit();
170         }
171     }
172
173     updateMapKeyValueOnMainParent(childrenProps: Array<DerivedFEProperty>){
174         if (this.property instanceof PropertyFEModel) {
175             const property: PropertyFEModel = <PropertyFEModel>this.property;
176             //Update only if all this property parents has key name
177             if (property.getParentNamesArray(childrenProps[0].propertiesName, []).indexOf('') === -1){
178                 angular.forEach(childrenProps, (prop:DerivedFEProperty):void => { //Update parent PropertyFEModel with value for each child, including nested props
179                     property.childPropUpdated(prop);
180                     if (prop.isChildOfListOrMap && prop.mapKey !== undefined) {
181                         property.childPropMapKeyUpdated(prop, prop.mapKey, true);
182                     }
183                 },this);
184                 //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)
185                 let parentNames = (<PropertyFEModel>property).getParentNamesArray(childrenProps[0].propertiesName, []);
186                 childrenProps[0].valueObj = _.get(property.valueObj, parentNames.join('.'), null);
187             }
188         }
189     }
190
191     childValueChanged = (property: DerivedFEProperty) => { //value of child property changed
192
193         if (this.property instanceof PropertyFEModel) { // will always be the case
194             if (this.property.getParentNamesArray(property.propertiesName, []).indexOf('') === -1) {//If one of the parents is empty key -don't save
195                 this.property.childPropUpdated(property);
196                 this.dataTypeService.checkForCustomBehavior(this.property);
197                 this.emitter.emit();
198             }
199         }
200     }
201
202     deleteListOrMapItem = (item: DerivedFEProperty) => {
203         if (this.property instanceof PropertyFEModel) {
204             this.removeValueFromParent(item);
205             this.property.flattenedChildren.splice(this.property.getIndexOfChild(item.propertiesName), this.property.getCountOfChildren(item.propertiesName));
206             this.expandChildById(item.propertiesName);
207         }
208     }
209
210     removeValueFromParent = (item: DerivedFEProperty) => {
211         if (this.property instanceof PropertyFEModel) {
212             let itemParent = (item.parentName == this.property.name)
213                 ? this.property : this.property.flattenedChildren.find(prop => prop.propertiesName == item.parentName);
214             if (!itemParent) {
215                 return;
216             }
217
218             if (item.derivedDataType == DerivedPropertyType.MAP && !item.mapInlist) {
219                 const oldKey = item.getActualMapKey();
220                 delete itemParent.valueObj[oldKey];
221                 if (itemParent instanceof PropertyFEModel) {
222                     delete itemParent.valueObjValidation[oldKey];
223                     itemParent.valueObjIsValid = itemParent.calculateValueObjIsValid();
224                 }
225                 this.property.childPropMapKeyUpdated(item, null);  // remove map key
226             } else {
227                 const itemIndex: number = this.property.flattenedChildren.filter(prop => prop.parentName == item.parentName).map(prop => prop.propertiesName).indexOf(item.propertiesName);
228                 itemParent.valueObj.splice(itemIndex, 1);
229                 if (itemParent instanceof PropertyFEModel) {
230                     itemParent.valueObjValidation.splice(itemIndex, 1);
231                     itemParent.valueObjIsValid = itemParent.calculateValueObjIsValid();
232                 }
233             }
234             if (itemParent instanceof PropertyFEModel) { //direct child
235                 this.emitter.emit();
236             } else { //nested child - need to update parent prop by getting flattened name (recurse through parents and replace map/list keys, etc)
237                 this.childValueChanged(itemParent);
238             }
239         }
240     }
241
242     updateChildKeyInParent(childProp: DerivedFEProperty, newMapKey: string) {
243         if (this.property instanceof PropertyFEModel) {
244             this.property.childPropMapKeyUpdated(childProp, newMapKey);
245             this.emitter.emit();
246         }
247     }
248
249     preventInsertItem = (property:DerivedFEProperty):boolean => {
250         if(property.type == PROPERTY_TYPES.MAP && Object.keys(property.valueObj).indexOf('') > -1 ){
251             return true;
252         }
253         return false;
254     }
255
256 }