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