Merge "Fix R3 model for OOF Policy Optimization"
[policy/engine.git] / POLICY-SDK-APP / src / main / webapp / app / policyApp / policy-models / Editor / PolicyTemplateController / DCAEMicroServicePolicyController.js
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2018 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 angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
22     $("#dialog").hide();
23     
24     $scope.policyNavigator;
25     $scope.isCheck = false;
26     $scope.savebutton = true;
27     $scope.refreshCheck = false;
28     
29     var layer = 0;
30     
31     if(!$scope.temp.policy.editPolicy  && !$scope.temp.policy.readOnly){
32         $scope.temp.policy = {
33                         policyType : "Config",
34                         configPolicyType : "Micro Service"
35         }
36     };
37     
38     $scope.refresh = function(){
39         if($scope.refreshCheck){
40                 $scope.policyNavigator.refresh();
41         }
42         $scope.modal('createNewPolicy', true);
43         $scope.temp.policy = "";
44     };
45     
46     $scope.modal = function(id, hide) {
47         return $('#' + id).modal(hide ? 'hide' : 'show');
48     };
49     
50     $('#ttlDate').datepicker({
51         dateFormat: 'dd/mm/yy',
52         changeMonth: true,
53         changeYear: true,
54         onSelect: function(date) {
55                 angular.element($('#ttlDate')).triggerHandler('input');
56         }
57     });
58     
59         if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly  != undefined){
60                 if ($scope.temp.policy.configName == undefined){
61                         $scope.isCheck = false;
62                 }else{
63                         $scope.isCheck = true;
64                 }
65         }else {
66                 $scope.isCheck = false;
67         }
68                 
69         PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
70                 var j = data;
71                 $scope.data = JSON.parse(j.data);
72                 console.log($scope.data);
73                 $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
74                 console.log($scope.onapNameDictionaryDatas);
75         }, function (error) {
76                 console.log("failed");
77         });
78
79         PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
80                 var j = data;
81                 $scope.data = JSON.parse(j.data);
82                 console.log($scope.data);
83                 $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
84                 console.log($scope.priorityDatas);
85         }, function (error) {
86                 console.log("failed");
87         });
88
89         PolicyAppService.getData('getDictionary/get_GroupPolicyScopeDataByName').then(function (data) {
90                 var j = data;
91                 $scope.data = JSON.parse(j.data);
92                 console.log($scope.data);
93                 $scope.groupPolicyScopeListDatas = JSON.parse($scope.data.groupPolicyScopeListDatas);
94                 console.log($scope.groupPolicyScopeListDatas);
95         }, function (error) {
96                 console.log("failed");
97         });
98
99         PolicyAppService.getData('getDictionary/get_MicroServiceConfigNameDataByName').then(function (data) {
100                 var j = data;
101                 $scope.data = JSON.parse(j.data);
102                 console.log($scope.data);
103                 console.log("$scope.data.microServiceConfigNameDictionaryDatas : " + $scope.data.microServiceConfigNameDictionaryDatas);
104                 if($scope.data.microServiceConfigNameDictionaryDatas){
105                     $scope.microServiceCongigNameDictionaryDatas = JSON.parse($scope.data.microServiceConfigNameDictionaryDatas);
106                 }
107                 console.log($scope.microServiceCongigNameDictionaryDatas);
108         }, function (error) {
109                 console.log("failed");
110         });
111
112         PolicyAppService.getData('getDictionary/get_MicroServiceLocationDataByName').then(function (data) {
113                 var j = data;
114                 $scope.data = JSON.parse(j.data);
115                 console.log($scope.data);
116                 $scope.microServiceLocationDictionaryDatas = JSON.parse($scope.data.microServiceLocationDictionaryDatas);
117                 console.log($scope.microServiceLocationDictionaryDatas);
118         }, function (error) {
119                 console.log("failed");
120         });
121
122         PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataByName').then(function (data) {
123                 var j = data;
124                 $scope.data = JSON.parse(j.data);
125                 console.log($scope.data);
126                 var inputModelList = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
127                 var unique = {};
128                 var uniqueList = [];
129                 for(var i = 0; i < inputModelList.length; i++){
130                         if(typeof unique[inputModelList[i]] == "undefined"){
131                                 unique[inputModelList[i]] = "";
132                                 uniqueList.push(inputModelList[i]);
133                         }
134                 }
135                 $scope.microServiceModelsDictionaryDatas = uniqueList;
136                 console.log($scope.microServiceModelsDictionaryDatas);
137         }, function (error) {
138                 console.log("failed");
139         });
140
141         PolicyAppService.getData('getDictionary/get_DCAEUUIDDataByName').then(function (data) {
142                 var j = data;
143                 $scope.data = JSON.parse(j.data);
144                 console.log($scope.data);
145                 $scope.dcaeUUIDDictionaryDatas = JSON.parse($scope.data.dcaeUUIDDictionaryDatas);
146                 console.log($scope.dcaeUUIDDictionaryDatas);
147         }, function (error) {
148                 console.log("failed");
149         });
150
151         PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
152                 var j = data;
153                 $scope.data = JSON.parse(j.data);
154                 console.log($scope.data);
155                 $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
156                 console.log($scope.riskTypeDictionaryDatas);
157         }, function (error) {
158                 console.log("failed");
159         });
160
161         PolicyAppService.getData('getDictionary/get_MicroServiceAttributeData').then(function (data) {
162                 var j = data;
163                 $scope.data = JSON.parse(j.data);
164                 console.log($scope.data);
165                 $scope.microServiceAttributeDictionaryDatas = JSON.parse($scope.data.microServiceAttributeDictionaryDatas);
166                 console.log($scope.microServiceAttributeDictionaryDatas);
167         }, function (error) {
168                 console.log("failed");
169         });
170             
171
172          $scope.choices = [];
173          $scope.attributeDatas = [{"attributes" : $scope.choices}];
174          addNewChoice = function(value) {
175                  console.log("input key : " + value);
176                  var isFoundInRuleData = false;
177                  if(value != undefined){
178                         if (value.startsWith('div.')){
179                                 value = value.replace('div.','');
180                         }
181                         
182                         console.log(" document.getElementById : div."+value);
183                         var parentElement = document.getElementById("div."+value);
184                         console.log("parentElement : " + parentElement);
185                         var div = document.getElementById(value+"@0");
186                         if(div != null){
187                                 var clone = div.cloneNode(true); 
188                                 var addElement = parentElement.childElementCount;
189                                 clone.id = ''+value+'@'+addElement;
190                                 clone.value = '';
191                                 if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ //if it's view or edit
192                                         if($scope.temp.policy.ruleData[clone.id] || $scope.temp.policy.editPolicy){  // Only append child if its value found in ruleData or edit mode
193                                                 if($scope.temp.policy.ruleData[clone.id]){
194                                                     clone.value = $scope.temp.policy.ruleData[clone.id];
195                                                     isFoundInRuleData = true;
196                                                 }
197                                                 console.log("  clone.value :" +  clone.value);
198                                                 console.log(" clone.id :" + clone.id);
199                                                 if(!isFoundInRuleData && isInitViewEdit){
200                                                         return;
201                                                 }
202                                                 if(!clone.className.includes("child_single")){
203                                                    clone.className += ' child_single'; //here cloned is single element
204                                                 }
205                                                 document.getElementById("div."+value).appendChild(clone);
206                                                 plainAttributeKeys.push(''+value+'@'+addElement);
207                                         }
208                                 }else{ //not view or edit
209                                         if(!clone.className.includes("child_single")){
210                                             clone.className += ' child_single'; //here cloned is single element
211                                         }
212                                         document.getElementById("div."+value).appendChild(clone);
213                                         plainAttributeKeys.push(''+value+'@'+addElement);
214                                 }
215                         }else{
216                                 
217                                 if(parentElement == null){
218                                         return;
219                                 }
220                                 div = document.getElementById("div."+value+"@0");
221                                 if(div){
222                                         
223                                         if(!div.className.includes('children_group border')){
224                                                 layer++;
225                                                 if(layer > 4){ 
226                                                         layer = 1
227                                                 };
228                                     div.className += ' children_group border' + layer; //here is div with a group of children.
229                                         }
230                                 }
231                                 var childElement = parentElement.firstElementChild;
232                                 var countParent = parentElement.childElementCount;
233                                 var childElementString = childElement.innerHTML;
234                                 var find = value+"@0";
235                                 var re = new RegExp(find, 'g');
236                                 childElementString = childElementString.replace(re,value+'@' + countParent);
237                                 var clone = childElement.cloneNode(true);
238                                 for (var ii = 0; ii < parentElement.childNodes.length; ii++){
239                             var childId = parentElement.childNodes[ii].id;
240                             if(ii = parentElement.childNodes.length){
241                                 var childnewId = childId.slice(0, -1);
242                                 var count = childId.slice(-1);
243                             }
244                         }
245                                 var countvalue = parseInt(count) + 1;
246                                 clone.id = childnewId+countvalue;
247                                 clone.value = '';
248                                 clone.innerHTML=childElementString;
249                                 document.getElementById("div."+value).appendChild(clone);
250                                 var selects = clone.getElementsByTagName("select");
251                                 var inputs = clone.getElementsByTagName("input");
252                                 var removeValues = [];
253                                 for(var i=0; i<inputs.length; i++){
254                                         if ($scope.temp.policy.ruleData!=undefined){
255                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
256                                                 console.log("  checkValue.value :" +  checkValue);
257                                                 console.log(" inputs["+i+"].id :" + inputs[i].id);
258                                                 if (checkValue!=undefined && checkValue != "undefined"){
259                                                         document.getElementById(inputs[i].id).value = checkValue;
260                                                                 plainAttributeKeys.push(inputs[i].id);
261                                                 } else {
262                                                         plainAttributeKeys.push(inputs[i].id);
263                                                 }
264                                         }else {
265                                                 plainAttributeKeys.push(inputs[i].id);
266                                         }
267                                 }
268                                 
269                                 for(var i=0; i<selects.length; i++){
270                                         if ($scope.temp.policy.ruleData!=undefined){
271                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
272                                                 if (checkValue!=undefined && checkValue!="undefined"){
273                                                         if($scope.temp.policy.ruleData != null){
274                                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
275                                                                 document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
276                                                                 plainAttributeKeys.push(selects[i].id);
277                                                         }
278                                                 } else {
279                                                         plainAttributeKeys.push(selects[i].id);
280                                                 }
281                                         }else {
282                                                 plainAttributeKeys.push(selects[i].id);
283                                         }
284                                 }
285                                 
286                                 for (var k=0; k<removeValues.length; k++){
287                                         var elem = document.getElementById(removeValues[k]);
288                                         elem.parentNode.removeChild(elem);
289                                 }
290                                 var ele = angular.element(document.getElementById("div."+value));
291                         $compile(ele.contents())($scope)
292                         }
293                  }
294          };
295          
296         
297          removeChoice = function(value) {
298                  console.log(value);
299                  if(value != undefined){
300                          var c = document.getElementById("div."+value).childElementCount;
301                          
302                          if(c == 1){
303                                  Notification.error("The original one is not removable.");
304                                  return;
305                          }      
306                          document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);     
307                  }
308          };
309          
310          function findVal(object, key) {
311                     var value;
312                     Object.keys(object).some(function(k) {
313                         if (k === key) {
314                             value = object[k];
315                             return true;
316                         }
317                         if (object[k] && typeof object[k] === 'object') {
318                             value = findVal(object[k], key);
319                             return value !== undefined;
320                         }
321                     });
322                     return value;
323         }
324          
325          $scope.pullVersion = function(serviceName) {
326                  console.log(serviceName);
327                  if(serviceName != undefined){
328                          var uuu = "policyController/getModelServiceVersioneData.htm";
329                          var postData={policyData: serviceName};
330                          $.ajax({
331                                  type : 'POST',
332                                  url : uuu,
333                                  dataType: 'json',
334                                  contentType: 'application/json',
335                                  data: JSON.stringify(postData),
336                                  success : function(data){
337                                          $scope.$apply(function(){
338                                                  $scope.microServiceModelsDictionaryVersionDatas = data[0].dcaeModelVersionData;
339                                          });
340                                  },
341                                  error : function(data){
342                                          alert("Error While Retriving the Template Layout Pattren.");
343                                  }
344                          });             
345                  }
346          };
347     
348     var splitDash = '-';
349         var splitEqual = '=';
350         var splitComma = ',';
351         var splitcolon = ':';
352         var splitsemicolon = ";";
353         var splitEnum = "],";
354         var plainAttributeKeys = [];
355         var matching = [];
356         var enumKeyList = [];
357         var dictionaryList = [];
358         var dictionaryNameList = [];
359         var isInitViewEdit = false;
360     $scope.addDataToFields = function(serviceName, version){
361         if(serviceName != null && version !=null){
362                 var service=serviceName+"-v"+version;
363                 var myNode = document.getElementById("DynamicTemplate");
364                 myNode.innerHTML = '';
365             var uuu = "policyController/getDCAEMSTemplateData.htm";
366             var postData={policyData: service};
367             
368             console.log("service: " +service);
369             
370             var dataOrderInfo = "";
371             
372             booleanTrueElements = [];
373
374             document.getElementById("msPolicyloader").style.visibility = "visible";
375             
376             $.ajax({
377                 type : 'POST',
378                 url : uuu,
379                 dataType: 'json',
380                 contentType: 'application/json',
381                 data: JSON.stringify(postData),
382                 success : function(data){
383                         
384                         document.getElementById("msPolicyloader").style.visibility = "hidden";
385                         
386                     $scope.$apply(function(){
387                         var plainAttributeKeys = [];
388                         $scope.dcaeModelData = data[0].dcaeModelData;
389                         $scope.dcaeJsonDate = data[0].jsonValue;
390                         $scope.dataOrderInfo = null;
391                         $scope.dataOrderInfo = data[0].dataOrderInfo;
392                         console.log("data[0].dataOrderInfo: " + data[0].dataOrderInfo);
393                         console.log("$scope.dataOrderInfo: " + $scope.dataOrderInfo);   
394                         
395                         if(data[0].allManyTrueKeys){
396                                 console.log("$scope.allManyTrueKeys: " + $scope.allManyTrueKeys);
397                         }
398                         console.log("$scope.dcaeJsonDate: " + $scope.dcaeJsonDate);     
399                         var attributes = $scope.dcaeModelData.attributes;                       
400                         console.log("attributes: " +attributes);                        
401                         var refAttributes = $scope.dcaeModelData.ref_attributes;
402                         var subAttributes =     $scope.dcaeModelData.sub_attributes;                            
403                         console.log("subAttributes: " + subAttributes); 
404                         console.log("refAttributes: " + refAttributes); 
405                         var headDefautlsData  = data[0].headDefautlsData;
406                         if(headDefautlsData != null){
407                                          $scope.temp.policy.onapName = headDefautlsData.onapName;
408                                          $scope.temp.policy.guard = headDefautlsData.guard;
409                                          $scope.temp.policy.riskType = headDefautlsData.riskType;
410                                          $scope.temp.policy.riskLevel = headDefautlsData.riskLevel;
411                                          $scope.temp.policy.priority = headDefautlsData.priority;
412                         }
413                         
414                         var enumAttributes = $scope.dcaeModelData.enumValues;
415                         var annotation = $scope.dcaeModelData.annotation;
416                         var dictionary = $scope.microServiceAttributeDictionaryDatas;
417
418                         if (annotation == null || annotation.length<1){
419                                 $scope.isCheck = true;
420                         }else {
421                                 $scope.isCheck = false;
422                                 var annoationList = annotation.split(splitComma);
423                                 for (k = 0; k < annoationList.length; k++){
424                                         var splitAnnotation = annoationList[k].split(splitEqual);
425                                         if (splitAnnotation[1].includes("matching-true")){
426                                                 matching.push(splitAnnotation[0].trim());
427                                         }
428                                 }
429
430                         }
431
432                         if (dictionary!= null && dictionary.length>1){
433                                 for (m=0; m < dictionary.length; m += 1){
434                                         var keyCompare = dictionary[m].name;
435                                         var valueCompare = dictionary[m].value;
436                                         var valueModel = dictionary[m].modelName;
437                                         var conpairService = serviceName;
438                                         if (valueModel.includes('-v')){
439                                                 conpairService = service;
440                                         }
441                                         if(valueModel.localeCompare(conpairService) == 0){
442                                                 console.log(valueCompare);      
443                                                 dictionaryList.push(dictionary[m]);
444                                                 if (!dictionaryNameList.includes(dictionary[m].name)){
445                                                         dictionaryNameList.push(dictionary[m].name)
446                                                 }
447                                         }
448                                 }
449                         }
450
451                                 $scope.temp.policy.ruleGridData = [];
452                                 
453                                 if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
454                                         dataOrderInfo = $scope.dataOrderInfo;
455                                 }
456                                 
457                                 $scope.jsonLayout($scope.dcaeJsonDate);
458                                 
459                     });
460                     
461                     if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){  // If it's veiw or edit
462                         isInitViewEdit = true;
463                         var checkData = [];
464                         var data = [];
465                             // If ruleData contains extra elements created by clicked add button 
466                             console.log("$scope.temp.policy.ruleData:" + $scope.temp.policy.ruleData);
467                                 if($scope.temp.policy.ruleData != null){
468                                         var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
469                                         propNames.forEach(function(name) {
470                                                 data.push(name);
471                                         });
472                                         
473                                         var extraElements = data;
474                                         
475                                             if(plainAttributeKeys != null){
476                                                         for(var b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
477                                                                 var newValue = plainAttributeKeys[b].split("*");
478                                                                 for(var a = 0; a < data.length; a++){
479                                                                         if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
480                                                                                 extraElements.splice(a, 1);
481                                                                         }
482                                                                 }
483                                                 }
484                                                 
485                                                 //--- Populate these extra elements created by clicked add button 
486                                                 for(var a = 0; a < extraElements.length; a++){                                  
487                                                         if(extraElements[a].includes("@")){
488                                                                 var index = extraElements[a].lastIndexOf("@");
489                                                                 if(index > 0){
490                                                                     // Get the number after @
491                                                                     var n = getNumOfDigits(extraElements[a], index+1);
492                                                                                         
493                                                                         var key = extraElements[a].substring(0, index+n+1); //include @x in key also by n+2 since x can be 1,12, etc
494                                                                         console.log("key: " + key);
495                                                                         checkData.push(key);
496                                                                 }
497                                                         }
498                                                 }
499                                                 var unique = checkData.filter(onlyUnique);
500                                                 var parentLevelElements = [];
501                                                 if(unique){
502                                                         //--- get all root level exta elments first (only contains one "@")
503                                                         for(var i =0; i < unique.length; i++){
504                                                                 var firstIndex = unique[i].indexOf("@");
505                                                                 var lastIndex = unique[i].lastIndexOf("@");
506                                                                 if(firstIndex == lastIndex){    
507                                                                         var newKey = unique[i].substring(0, firstIndex);
508                                                                         console.log("root element: " + newKey);
509                                                                         parentLevelElements.push(newKey);
510                                                                         unique[i] = "*processed*";
511                                                                 }
512                                                         }                                                       
513                                                 }
514                                                 
515                                                 
516                                                 for (var i = 0; i < $scope.labelManyKeys.length; i++) {
517                                                     var label = $scope.labelManyKeys[i];                                                            
518                                                     if(parentLevelElements){
519                                                         for (var k = 0; k < parentLevelElements.length; k++){
520                                                                 if(label == parentLevelElements[k]){
521                                                                         addNewChoice(label);
522                                                                 }
523                                                         }                                                                       
524                                                     }                                                                           
525                                                 }
526                                                 
527                                                 //if no layout order info, keep the process as before
528                                                 if(!dataOrderInfo){
529                                                         for(var i =0; i < unique.length; i++){
530                                                                 if(unique[i] != "*processed*"){
531                                                                         var index = unique[i].lastIndexOf("@");
532                                                                         var newKey = unique[i].substring(0, index);
533                                                                         console.log("newKey: " + newKey);       
534                                                                         
535                                                                         var newElement = document.getElementById("div."+unique[j]);
536                                                                         //check weather it has been created already
537                                                 if(newElement != null){
538                                                         continue;
539                                                 }else{
540                                                         newElement = document.getElementById(unique[j]);
541                                                         if(newElement != null){
542                                                                 continue;
543                                                         }
544                                                 } 
545                                                 
546                                                                         if(newKey){
547                                                                                 addNewChoice(newKey);
548                                                                         }
549                                                                 }
550                                                         }
551                                                 }else{
552                                                                 //---reset to default
553                                                                 dataOrderInfo = [];
554                                                                 $scope.labelManyKeys = [];
555                                                                 
556                                                                 //---process none labels
557                                                                 for (var j = 0; j < unique.length; j++){
558                                                                         if(unique[j] != "*processed*"){
559                                                                                 // if not created yet
560                                                                                 if(!document.getElementById(unique[j])){
561                                                                                         var index = unique[j].lastIndexOf("@");
562                                                                                         var newKey = unique[j].substring(0, index);
563                                                                                         
564                                                                                         var newElement = document.getElementById("div."+unique[j]);
565                                                                                         
566                                                                                         //check weather it has been created already
567                                                         if(newElement != null){
568                                                                 continue;
569                                                         }else{
570                                                                 newElement = document.getElementById(unique[j]);
571                                                                 if(newElement != null){
572                                                                         continue;
573                                                                 }
574                                                         } 
575                                                         //if not created yet, then create it.                                                                                           
576                                                                                         addNewChoice(newKey);
577                                                                                    
578                                                                                 }
579                                                                         }
580                                                                 }
581                                                         }
582                                             }
583                                 }
584
585                     }
586                     var ele = angular.element(document.getElementById("DynamicTemplate"));
587                         $compile(ele.contents())($scope);
588                     $scope.$apply();
589                     isInitViewEdit = false;                   
590                     
591                 },
592                 error : function(data){
593                     alert("Error While Retriving the Template Layout Pattren.");
594                 }
595             });
596
597         }
598     };
599     
600     function getNumOfDigits(str_value, index){
601                 // Get the number after @
602                 var str = str_value.substring(index, str_value.length); 
603                 var c = '';
604                 var n = 0;
605                 for (var x = 0; x < str.length; x++){                                                                   
606                     c = str.charAt(x);
607                             if(!isNaN(c)){ 
608                 n++;                                                     
609                     }else{
610                 break;
611             }
612                 }
613                 return n;
614     }
615     
616     function getDictionary(attribute){
617         var dicName = attribute;
618         if(attribute){
619            if(attribute.includes(":")){
620                    dicName = attribute.split(":")[0];
621            }
622         }
623             var dictionaryRegExp = new RegExp(dicName);
624             listemunerateValues = [];
625             if (dictionaryRegExp.test(dictionaryNameList)) {
626                         for (p=0; p < dictionaryList.length; p += 1) {
627                                 if (dicName == dictionaryList[p].name) {
628                                         listemunerateValues.push(dictionaryList[p].value);
629                                 }
630                         }
631             }
632             return listemunerateValues;
633     }
634     
635     function getList(attribute) {
636                 var enumName = attribute;
637                 console.log("In getList: attribute => " + attribute);
638                 if(attribute){
639                    if(attribute.includes(":")){
640                            enumName = attribute.split(":")[0];
641                    }
642                 }   
643             var baseEnum = $scope.dcaeModelData.enumValues;
644             var enumList = [];
645             if(baseEnum != null){
646                 enumList = baseEnum.split(splitEnum);
647             }
648                 var enumAttributes;
649                 var patternTest = new RegExp(enumName);
650                 for (k=0; k < enumList.length; k += 1){
651                         if(patternTest.test(enumList[k]) == true){
652                                 enumAttributes = enumList[k].trim();
653                 }
654         }
655
656          if(enumAttributes){
657                 enumAttributes = enumAttributes.replace("[", "");
658                 enumAttributes = enumAttributes.replace("]", "");
659                 enumAttributes = enumAttributes.replace(/ /g, '');
660                         var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
661                         listemunerateValues  = dropListAfterCommaSplit[1].split(splitComma);
662                         //enumKeyList.push(attribute); 
663                 return listemunerateValues;
664          }
665          
666             return [];
667             }
668             
669             function getBooleanList(){
670                 var booleanList = [];
671                 booleanList.push(true);
672                 booleanList.push(false);
673                 return booleanList;
674             }
675             
676
677             function isArray(arrayTest) {
678                 return Object.prototype.toString.call(arrayTest) === '[object Array]';
679             }
680             var lableList = [];
681             
682             $scope.layOutElementList = [];
683             $scope.layOutOnlyLableList = [];
684             
685             var elementOrderNum = 0;
686             
687                 function deconstructJSON(layOutData, level , name) {
688
689                          var array = false;
690                          var label = level;
691                          var stringValue = "java.lang.String";
692                          var string = "string";
693                          var intValue = "int";
694                          var integerValue = "integer";
695                          var double = "double";
696                          var boolean = "boolean";
697                          var baseLevel = level;
698                          var list = "list";
699                          var String = "String";
700                          
701                          var attributekey = "";
702                          
703                         if (name.length > 1){
704                                 label = label + name + '.';
705                         }
706                         
707                     for (key in layOutData) {
708                         array = isArray(layOutData[key]);
709                         console.log("key: " + key , "value: " + layOutData[key]);
710                 
711                         if (!!layOutData[key] && typeof(layOutData[key])=="object") {
712                                 
713                                 if (array==false && key!=="0"){
714                                         
715                                         if($scope.dataOrderInfo){
716                                             var labelObject = {"label" : key, "level" : label, "array" : array};
717                                             //save it to the list
718                                             $scope.layOutOnlyLableList.push(labelObject);
719                                             
720                                         }else {
721                                                 //call label layout
722                                                 $scope.labelLayout(label, key, array );
723                                         }
724                                         
725                                 }
726                                 
727                                 if (array == true && key!=0){
728                                         lableList.push(key);
729                                 }
730                                 
731                                 if (lableList.length > 0){
732                                         array = true;
733                                 }
734                                 if ( key==="0"){
735                                         var newKey = lableList.pop();
736                                         
737                                         if($scope.dataOrderInfo){
738                                                 
739                                                 var labelObject = {"label" : newKey, "level" : baseLevel, "array" : array};
740                                                 //save it to the list
741                                                 $scope.layOutOnlyLableList.push(labelObject);
742                                                 
743                                         }else {
744                                                 //call label layout 
745                                             $scope.labelLayout(baseLevel, newKey, array );
746                                         }
747                                         
748                                         if (array){
749                                                 label = baseLevel + newKey + '@0.';
750                                         } else {
751                                                 label = baseLevel + newKey + '.';
752                                         }
753                                 }
754                                 deconstructJSON(layOutData[key] , label, key);
755                         } else {
756                                 var attirbuteLabel = label;
757                                 var defaultValue='';
758                                 var description='';
759                                 var isRequired = false;
760                                 if (layOutData[key].includes('defaultValue-')){
761                                         defaultValue = layOutData[key].split('defaultValue-')[1];
762                                 }
763                                 
764                                 if (layOutData[key].includes('description-')){
765                                         description = layOutData[key].split('description-')[1];
766                                 }                               
767                                 
768
769                                 if (key==="0"){
770                                         array = true;
771                                         attributekey = lableList.pop();
772                                         attirbuteLabel = baseLevel;
773                                 } else {
774                                         attributekey = key.split();
775                                 }
776                                 
777                                 if (layOutData[key].includes('required-true')){
778                                         isRequired = true;
779                                 }
780                                 
781                                 var subAttributes = $scope.dcaeModelData.sub_attributes;
782                                 
783                                 if(subAttributes){                                      
784                                         var jsonObject = JSON.parse(subAttributes);     
785                                         
786                                     var lablInfo = findVal(jsonObject, attributekey);
787                                         console.log("deconstructJSON:findValue : " + attributekey +": "+ lablInfo);
788                                         if (lablInfo){
789                                                 if(lablInfo.includes('required-true')){
790                                                         isRequired = true;
791                                                 }       
792                                                 if(lablInfo.includes('defaultValue-')){
793                                                         defaultValue = lablInfo.split('defaultValue-')[1];
794                                                 }
795                                                 
796                                                 if(lablInfo.includes('description-')){
797                                                         description = lablInfo.split('description-')[1];
798                                                 }
799                                                 
800                                         }else{                                  
801                                            var allkeys = Object.keys(jsonObject);
802                                            if(allkeys){
803                                                    for (var k = 0; k < allkeys.length; k++) {
804                                                           var keyValue = allkeys[k];
805                                                           console.log(" keyValue:jsonObject["+keyValue+ "]: " + jsonObject[keyValue]);
806                                                           if(jsonObject[keyValue]){
807                                                                  var tempObject = jsonObject[keyValue];
808                                                                  if(tempObject && tempObject[key]){
809                                                                  if (tempObject[key].includes('required-true')){
810                                                                         isRequired = true;
811                                                                  }      
812                                                                  
813                                                                  if(tempObject[key].includes('defaultValue-')){
814                                                                         defaultValue = tempObject[key].split('defaultValue-')[1];
815                                                                  }
816                                                                  
817                                                                  if(tempObject[key].includes('description-')){
818                                                                          description = tempObject[key].split('description-')[1];
819                                                                   }
820
821                                                                  }
822                                                           }
823                                                    }                                            
824                                            }                                    
825                                         } 
826                                 }
827                                 
828                                 var elementObject = {};
829                                 switch (layOutData[key].split(splitcolon)[0]){
830                                 
831                                         case stringValue:
832                                         case string:
833                                                 if($scope.dataOrderInfo){                                                       
834                                                         elementOrderNum++;
835                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"text", "description":description};
836                                                         $scope.layOutElementList.push(elementObject);
837                                                 }else{
838                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
839                                                 }
840                                                 break;                                          
841                                         case intValue: 
842                                         case integerValue: 
843                                                 if($scope.dataOrderInfo){
844                                                         elementOrderNum++;
845                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"number" , "description":description};
846                                                         $scope.layOutElementList.push(elementObject);
847                                                 }else{
848                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
849                                                 }
850                                                 break;                                          
851                                         case double:
852                                                 if($scope.dataOrderInfo){
853                                                         elementOrderNum++;
854                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"double",  "description":description};
855                                                         $scope.layOutElementList.push(elementObject);                                                   
856                                                 }else{
857                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
858                                                 }
859                                                 break;
860                                         case boolean:
861                                                 if($scope.dataOrderInfo){
862                                                         elementOrderNum++;
863                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"boolean", "description":description};
864                                                         $scope.layOutElementList.push(elementObject);
865                                                 }else{
866                                                         $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], getBooleanList());
867                                                 }
868                                                 break;
869                                         default:
870                                                 if (layOutData[key].includes('dictionary-')){
871                                                         var list = getDictionary(layOutData[key].split('dictionary-')[1]);
872                                                 }else{
873                                                         //--- get dropdown values from enumValues
874                                                         var list = getList(layOutData[key]);
875                                                 }
876                                                 if (list.length===0){ //not dropdown element
877                                                         if($scope.dataOrderInfo){
878                                                                 elementOrderNum++;
879                                                                 elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"text", "description":description};
880                                                                 $scope.layOutElementList.push(elementObject);
881                                                                 
882                                                         }else{
883                                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
884                                                         }                                                       
885                                                 }else{
886                                                         if($scope.dataOrderInfo){
887                                                                 elementOrderNum++;
888                                                                 elementObject = {"id": elementOrderNum, "attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "list":list, "type":"dropBox", "description":description};
889                                                                 $scope.layOutElementList.push(elementObject);                                                           
890                                                         }else{
891                                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], list, isRequired);
892                                                         }
893                                                 }
894                                                 break;
895                                 }
896                         }
897                     }
898                 }  
899                 
900                 
901             $scope.validContionalRequired = function(parentId) {
902                 console.log("ng-blur event: parentId : " + parentId);
903                 var c = document.getElementById(parentId).children;
904                 var i;
905                 var hasValue = false;
906                 for (i = 0; i < c.length; i++) {
907                         if(c[i].getAttribute("data-conditional")){
908                             console.log(c[i].getAttribute("data-conditional"));
909                             console.log(c[i].value);
910                             if(c[i].value != null && c[i].value.trim() != ""){
911                                 hasValue = true;
912                             }
913                         }
914                 }
915
916                     for (i = 0; i < c.length; i++) {
917                         if(c[i].getAttribute("data-conditional")){
918                                 if(hasValue){
919                                     c[i].setAttribute("required", true);
920                                 }else{
921                                         c[i].removeAttribute("required");
922                                 }
923                         }
924                     }           
925              }
926                                 
927             $scope.jsonLayout = function(layOutData){
928                 
929                    deconstructJSON(layOutData , "", "");
930                    
931                    var orderValue = $scope.dataOrderInfo;
932                    var layOutElementList = $scope.layOutElementList;
933                    var labelList = $scope.layOutOnlyLableList;
934                     
935                    //reset to default
936                    elementOrderNum = 0;
937                    $scope.layOutElementList = [];
938                    $scope.layOutOnlyLableList = [];
939                    
940                    // Only layout in order if order info provided
941                    if(orderValue){
942                            
943                            if(orderValue.includes("[")){
944                                   orderValue = orderValue.replace("[", "") ;
945                                   orderValue = orderValue.replace("]", "") ;
946                            }
947                            
948                            orderValue = orderValue.split(',') ;
949                            
950                            for (var i = 0; i < orderValue.length; i++) {
951                                    console.log("orderValue["+i+"]"+  orderValue[i]);
952                                    var key = orderValue[i].trim();
953                                  
954                                     //--- Create labels first {"label" : newKey, "level" : baseLevel, "array" : array};
955                                    if(labelList){
956                                            for (var k = 0; k < labelList.length; k++){
957                                                    
958                                                   var label = labelList[k].label.toString().trim();
959                                                   var level = labelList[k].level.toString().trim();
960                                                   var array = labelList[k].array;
961                                                   
962                                                   if(key == label){                                                       
963                                                          $scope.labelLayout(level, label, array);
964                                                          //in case to have duplicate label names
965                                                          labelList[k].label = "*processed*";
966                                                          break;
967                                                   }
968                                            }
969                                    }
970                                    //--- then layout each element based on its order defined in YAML file
971                                    for (var j = 0; j < layOutElementList.length; j++) { 
972                                            
973                                            var attributekey = layOutElementList[j].attributekey.toString().trim();                                         
974                                         
975                                            if(key == attributekey){     
976
977                                                    var attirbuteLabel = layOutElementList[j].attirbuteLabel.toString().trim();
978                                                    var defaultValue = layOutElementList[j].defaultValue.toString().trim();
979                                                    var description = layOutElementList[j].description;
980                                                    var isRequired = layOutElementList[j].isRequired;
981                                                    
982                                                    console.log("layOutElementList[" +j+ "]: id:" + layOutElementList[j].id + ", attributekey:"+ layOutElementList[j].attributekey + ", attirbuteLabel:" + layOutElementList[j].attirbuteLabel);
983                                                    console.log("layOutElementList[" +j+ "]: type:" + layOutElementList[j].type);
984                                                    if (layOutElementList[j].type == "dropBox"){ 
985                                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, layOutElementList[j].array, defaultValue, layOutElementList[j].list, isRequired, description);
986                                         
987                                                    }else{
988                                                             $scope.attributeBox(attributekey, layOutElementList[j].array, attirbuteLabel, defaultValue, isRequired, layOutElementList[j].type, description);    
989         
990                                                    }
991                                                    
992                                                    //in case to have duplicate attribute names
993                                                    layOutElementList[j].attributekey = "*processed*";
994                                                    break;
995                                            }
996                                    }
997                            }
998                    }
999             }
1000             
1001             
1002             $scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType,  description){
1003                         $scope.temp.policy.ruleGridData.push(attibuteKey);                      
1004                 var br = document.createElement("BR");
1005                 
1006                 var label = document.createElement("Label");
1007                 var labeltext = null;
1008                 var requiredLabName = "";
1009                 if (matching.includes(attibuteKey)){
1010                         labeltext = document.createTextNode(attibuteKey + "*!");        
1011                         isRequired = true;  //set required as true for matching element
1012                 }else {
1013                         if(isRequired){
1014                                 requiredLabName = attibuteKey + " * ";
1015                                 labeltext = document.createTextNode(requiredLabName);
1016                         }else{
1017                             labeltext = document.createTextNode(attibuteKey);   
1018                         }
1019                 }
1020
1021                 
1022                 var divID = labelValue;
1023                 
1024                 if (labelValue.length  < 1){
1025                         divID = "DynamicTemplate";
1026                 }else if (labelValue.endsWith('.')){
1027                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
1028                 }
1029                 
1030                 label.appendChild(labeltext);
1031                 
1032                 var textField = document.createElement("INPUT");
1033                 
1034                 textField.setAttribute("class" , "form-control");
1035                 if(dataType){
1036                            if(dataType == "double"){
1037                                    textField.setAttribute("type" , "number");
1038                                    textField.setAttribute("step" , "any");
1039                                    
1040                            }else if(dataType == "boolean"){  //gw1218 testing boolean
1041                                             var booleanDiv = document.createElement("div");
1042                                                 
1043                                                 booleanDiv.setAttribute("class" , "onoffswitch");
1044                                                 
1045                                                 //var checkField = document.createElement("INPUT");
1046                                                 textField.setAttribute("type" , "checkbox");
1047                                                 textField.setAttribute("name" , "onoffswitch");
1048                                                 textField.setAttribute("class" , "onoffswitch-checkbox");
1049                                                 textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
1050                                                 if(defaultValue && defaultValue == "true") {
1051                                                         textField.setAttribute("checked" , "true");
1052                                                 }else{
1053                                                         textField.setAttribute("checked" , "false");
1054                                                 }
1055
1056                                                 var booleanlabel = document.createElement("Label");
1057                                                 booleanlabel.setAttribute("class" , "onoffswitch-label");
1058                                                 booleanlabel.setAttribute("for" , ''+labelValue +attibuteKey+'');
1059                                         
1060                                                 var span1 = document.createElement("span");
1061                                                 span1.setAttribute("class" , "onoffswitch-inner");
1062                                                 
1063                                                 var span2 = document.createElement("span");
1064                                                 span2.setAttribute("class" , "onoffswitch-switch"); 
1065                                                 
1066                                                 
1067                                                 booleanlabel.appendChild(span1);        
1068                                                 booleanlabel.appendChild(span2);        
1069                                                 booleanDiv.appendChild(textField);      
1070                                                 booleanDiv.appendChild(booleanlabel);    
1071                                                 
1072                                                 document.getElementById(divID).appendChild(label);  
1073                                                 document.getElementById(divID).appendChild(booleanDiv);         
1074
1075                                                 //return;
1076                            } else{
1077                               textField.setAttribute("type" , dataType);
1078                            }
1079                            
1080                                 
1081
1082                 }
1083                 
1084                 if(dataType != "boolean"){
1085                         textField.setAttribute("style" , "width:300px;");
1086                         textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
1087                         if(description && description != "null"){
1088                                 textField.setAttribute("title", description);
1089                         }
1090                 }
1091
1092                 var checkKey;
1093                 var id = "";
1094                 if(attributeManyKey){
1095                         checkKey = labelValue + attibuteKey+'@0';
1096                         textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+''); 
1097                         var divTag = document.createElement("div");
1098                         divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
1099                         var addButton = document.createElement("BUTTON");
1100                         var buttonaddLabel = document.createTextNode("+");       
1101                         addButton.appendChild(buttonaddLabel); 
1102                         addButton.setAttribute("id", labelValue + attibuteKey);
1103                         addButton.setAttribute("class", "btn btn-add-remove");
1104                         addButton.setAttribute("onclick" ,  'addNewChoice("'+labelValue + attibuteKey+'");');
1105                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
1106                         var removeButton = document.createElement("BUTTON");
1107                         var buttonremoveLabel = document.createTextNode("-");       
1108                         removeButton.appendChild(buttonremoveLabel); 
1109                         removeButton.setAttribute("class", "btn btn-add-remove");
1110                         removeButton.setAttribute("onclick" ,  'removeChoice("'+labelValue + attibuteKey+'");');
1111                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
1112                         document.getElementById(divID).appendChild(addButton); 
1113                         document.getElementById(divID).appendChild(removeButton); 
1114                         document.getElementById(divID).appendChild(label); 
1115                         id = "div."+labelValue+attibuteKey;
1116                         //var divTag = document.createElement("div");
1117                         divTag.setAttribute("id", id); 
1118                         document.getElementById(divID).appendChild(divTag);
1119                         textField.className += ' first_child';  
1120                         if(isRequired){
1121                                 textField.setAttribute("required", "true");
1122                         }       
1123                         
1124                         divTag.appendChild(textField);                  
1125                         document.getElementById(divID).appendChild(divTag); 
1126                         
1127                 }else if (dataType != "boolean"){
1128                         checkKey = labelValue + attibuteKey;
1129                         textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
1130                         if(document.getElementById(divID).hasAttribute('required') || !document.getElementById(divID).hasAttribute('data-conditional')){
1131                                 if(requiredLabName.includes("*") || isRequired){
1132                                         textField.setAttribute("required", "true");
1133                                 }
1134                         }else if (document.getElementById(divID).hasAttribute('data-conditional')){
1135                                 if(requiredLabName.includes("*")){                                      
1136                                         var requiredNode = document.createElement('span');
1137                                         requiredNode.setAttribute("class", "mstooltip");
1138                                         requiredNode.textContent = "?";
1139                                         label.appendChild(requiredNode);
1140                                         
1141                                         var requiredNodeToolTip = document.createElement('span');
1142                                         requiredNodeToolTip.setAttribute("class", "tooltiptext");
1143                                         requiredNodeToolTip.textContent = "Conditional Required";
1144                                         requiredNode.appendChild(requiredNodeToolTip);
1145                                         
1146                                         textField.setAttribute("data-conditional", divID);
1147                                         textField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
1148                                 }
1149                         }
1150             
1151                         document.getElementById(divID).appendChild(label);  
1152                         document.getElementById(divID).appendChild(textField);  
1153                         document.getElementById(divID).appendChild(br); 
1154
1155                 }
1156
1157                 if(dataType != "boolean" && divID.includes("@0") && divID.includes("div.")){
1158                         var firstChild_Id = divID.split("@0")[0];
1159                         var firstChild_element = document.getElementById(firstChild_Id);
1160                         if(firstChild_element){
1161                         
1162                                 if(!firstChild_element.className.includes('children_group border')){
1163                                         layer++;
1164                                         if(layer > 4){ 
1165                                                 layer = 1
1166                                         };
1167                                         firstChild_element.className += ' children_group border' + layer; //here is div with a group of children.
1168                                 }
1169                         }
1170                 }
1171                 console.log('firstChild_Id: ' + firstChild_Id);
1172                 console.log('divID: ' + divID);
1173                 
1174                 if(dataType != "boolean" && defaultValue.length > 0){   
1175                         if(defaultValue.includes(":")){
1176                                 defaultValue = defaultValue.split(":")[0];
1177                                 if(defaultValue === "NA") {
1178                                         defaultValue = "";
1179                                 }                               
1180                         }
1181                         if(defaultValue != "undefined" && defaultValue != undefined && defaultValue != "null"){
1182                         document.getElementById(checkKey).value = defaultValue;
1183                         }
1184                 }
1185                 
1186                 if($scope.temp.policy.ruleData != null){
1187                         //document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
1188                         if (attributeManyKey){
1189                                 var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
1190                                 if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
1191                                     document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
1192                                 }
1193                         }else{
1194                                 if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
1195                                     document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
1196                                 }
1197                         }
1198                 } 
1199                 
1200                 if (dataType != "boolean"){
1201                     plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey);     
1202                 }else{
1203                     plainAttributeKeys.push(labelValue + attibuteKey+'*'+"boolean");    
1204                 }
1205     };
1206   
1207     $scope.labelManyKeys = [];
1208     $scope.labelLayout = function(labelValue, lableName, labelManyKey ){
1209                 var label = document.createElement("Label")
1210                 var divID = labelValue;
1211                 if (labelValue.endsWith('.')){
1212                         var workingLabel = labelValue.substring(0, labelValue.length-1);
1213                 }else {
1214                         var workingLabel = labelValue;
1215                 }
1216                 
1217                 if (labelValue.length  < 1){
1218                         divID = "DynamicTemplate";
1219                 } else if (labelValue.endsWith('.')){
1220                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
1221                 }
1222                 
1223                 var subAttributes = $scope.dcaeModelData.sub_attributes;
1224             var jsonObject = JSON.parse(subAttributes); 
1225             var lablInfo = findVal(jsonObject, lableName);
1226                 console.log("findValue : " + lableName +": "+ lablInfo);
1227                 var star = "";
1228                 var required = null;
1229                 if(lablInfo){
1230                         if(typeof lablInfo === 'string' ){
1231                            if(lablInfo.includes("required-true")){
1232                                    star = " *";
1233                                    required = true;
1234                             }else if (lablInfo.includes("required-false")){
1235                                    required = false
1236                             }
1237                         }
1238                 }
1239                 
1240                 var labeltext = document.createTextNode(lableName + star);
1241         
1242                 label.appendChild(labeltext);
1243
1244
1245                 if(labelManyKey){
1246                         var addButton = document.createElement("BUTTON");
1247                         var buttonLabel = document.createTextNode("+");       
1248                         addButton.appendChild(buttonLabel); 
1249                         addButton.setAttribute("class", "btn btn-add-remove");
1250                         addButton.setAttribute("onclick" ,  'addNewChoice("'+labelValue + lableName+'");');
1251                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
1252                         var removeButton = document.createElement("BUTTON");
1253                         var buttonremoveLabel = document.createTextNode("-");       
1254                         removeButton.appendChild(buttonremoveLabel); 
1255                         removeButton.setAttribute("class", "btn btn-add-remove");
1256                         removeButton.setAttribute("onclick" ,  'removeChoice("'+labelValue +lableName+'");');
1257                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly"); 
1258                         document.getElementById(divID).appendChild(addButton); 
1259                         document.getElementById(divID).appendChild(removeButton);
1260                         document.getElementById(divID).appendChild(label);
1261                         var id = "div."+labelValue+lableName;
1262                         var divTag = document.createElement("div");
1263                         divTag.setAttribute("id", id); 
1264                         document.getElementById(divID).appendChild(divTag);
1265                         
1266                         var divTag = document.createElement("div");
1267                         divTag.setAttribute("id", id +'@0');  
1268                         
1269                         if(!divTag.className.includes('children_group border')){
1270                                 layer++;
1271                                 if(layer > 4){ 
1272                                         layer = 1
1273                                 };
1274                                 divTag.className += ' children_group border' + layer; //here is div with a group of children.
1275                         }
1276                         if(required){
1277                            divTag.setAttribute("required", required);  
1278                         }else if(required == false){
1279                            divTag.setAttribute("data-conditional", "yes");  
1280                         }
1281                         
1282                         document.getElementById(id).appendChild(divTag);
1283                         
1284                         $scope.labelManyKeys.push(lableName);
1285                         
1286                 }else{
1287                         var divTag = document.createElement("div");
1288                         divTag.setAttribute("id", "div."+labelValue+lableName);
1289                         
1290                         if(!divTag.className.includes('children_group border')){
1291                                 layer++;
1292                                 if(layer > 4){ 
1293                                         layer = 1
1294                                 };
1295                                 divTag.className += ' children_group border' + layer; //here is div with a group of children.
1296                         }
1297                         if(required){
1298                             divTag.setAttribute("required", required);  
1299                         }else if(required == false){
1300                                 divTag.setAttribute("data-conditional", "yes");  
1301                         }  
1302                         document.getElementById(divID).appendChild(label);  
1303                         document.getElementById(divID).appendChild(divTag);                     
1304                 }
1305     };
1306
1307     $scope.dropBoxLayout = function(labelLevel, attributeName, many , defaultValue, listemunerateValues, isRequired, description){
1308                         var br = document.createElement("BR");
1309                 
1310                         if (labelLevel.length  < 1){
1311                                         var divID = "DynamicTemplate";
1312                         } else if (labelLevel.endsWith('.')){
1313                                         var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
1314                         }       
1315                 
1316                 
1317                         var label = document.createElement("Label")
1318                         
1319                         var refAttributes = $scope.dcaeModelData.ref_attributes;
1320                         if(isRequired != true && refAttributes){ //check refAttributes also             
1321                                         var refAttributesList = refAttributes.split(splitComma);
1322                                         for (k = 0; k < refAttributesList.length; k++){
1323                                         var refAttribute = refAttributesList[k].split(splitEqual);                      
1324                                         if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
1325                                                 isRequired = true;
1326                                         }
1327                                         }
1328                         }
1329                         
1330                         if (matching.includes(attributeName)){
1331                                 var labeltext = document.createTextNode(attributeName + "*!");
1332                                 label.appendChild(labeltext);
1333                                 isRequired = true;  //set required as true for matching element
1334                         }else {
1335                                 var labeltext = document.createTextNode(attributeName);         
1336                                 if(isRequired){
1337                                     var requiredLabName = attributeName+ " * ";
1338                                         labeltext = document.createTextNode(requiredLabName);
1339                                 }else{
1340                                     labeltext = document.createTextNode(attributeName); 
1341                                 }
1342                         
1343                             label.appendChild(labeltext);               
1344                         }
1345                         label.appendChild(labeltext);
1346                         // if this field is required, but its parent is not required
1347                         if(isRequired && document.getElementById(divID).hasAttribute('data-conditional')){
1348                                 var requiredNode = document.createElement('span');
1349                                 requiredNode.setAttribute("class", "mstooltip");
1350                                 requiredNode.textContent = "?";
1351                                 label.appendChild(requiredNode);
1352                                         
1353                                 var requiredNodeToolTip = document.createElement('span');
1354                                 requiredNodeToolTip.setAttribute("class", "tooltiptext");
1355                                 requiredNodeToolTip.textContent = "Conditional Required";
1356                                 requiredNode.appendChild(requiredNodeToolTip);
1357
1358                         }
1359                 
1360                         var listField = document.createElement("SELECT");
1361                         listField.setAttribute("class" , "form-control");
1362                         listField.setAttribute("style" , "width:300px;");
1363                         listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
1364                         
1365                         if(description && description != "null"){
1366                                 listField.setAttribute("title", description);
1367                         }
1368                         
1369                         if(isRequired){
1370                             if(document.getElementById(divID).hasAttribute('data-conditional')){
1371                                 listField.setAttribute("data-conditional", divID);
1372                                 listField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
1373                             }else{
1374                                         listField.setAttribute("required", true);
1375                             }
1376                         }
1377                         if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
1378                                 var optionFirst = document.createElement('option');
1379                                 optionFirst.setAttribute('value', "");
1380                                 listField.appendChild(optionFirst);     
1381                         }
1382                         
1383                         for (i=0; i < listemunerateValues.length; i += 1) {
1384                                 if(typeof listemunerateValues[i] == "string" && listemunerateValues[i].includes("equal-sign")){
1385                                         listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
1386                                 }
1387                                 
1388                             option = document.createElement('option');
1389                             option.setAttribute('value', listemunerateValues[i]);
1390                             option.appendChild(document.createTextNode(listemunerateValues[i]));
1391                             option.setAttribute('value', listemunerateValues[i]);
1392                             listField.appendChild(option);
1393                         }
1394                         listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
1395                         
1396                         enumKeyList.push(attributeName);
1397                         
1398                         document.getElementById(divID).appendChild(label);  
1399                         document.getElementById(divID).appendChild(br); 
1400                                         
1401                         if(many == true){
1402                                 document.getElementById(divID).appendChild(listField).multiple = true;
1403                                 plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
1404                         }else {
1405                                 document.getElementById(divID).appendChild(listField).multiple = false;
1406                                 plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
1407                                 
1408                                 if (defaultValue){
1409                                         if(defaultValue.includes(':')){
1410                                            defaultValue = defaultValue.split(':')[0];
1411                                         }
1412                                         var location = listemunerateValues.indexOf(defaultValue);
1413                                         document.getElementById(labelLevel +attributeName).options[location+1].selected = true;
1414                                 }
1415                         }
1416                 
1417                         if($scope.temp.policy.ruleData != null){
1418                                 if (many == true){
1419                                         document.getElementById(labelLevel +attributeName).options[0].selected = false;
1420                                         for (i=0; i < listemunerateValues.length; i += 1) {
1421                                                 var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
1422                                                 if (testValue === undefined){
1423                                                         testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
1424                                                         }
1425                                                 var location = listemunerateValues.indexOf(testValue);
1426                                                 if (location!=-1){
1427                                                         document.getElementById(labelLevel +attributeName).options[location].selected = true;
1428                                                         }
1429                                                 }                       
1430                                         }else {
1431                                                     if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
1432                                             document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];        
1433                                                     }
1434                                         }
1435                                 }
1436                     };
1437     
1438     function onlyUnique(value, index, self) { 
1439         return self.indexOf(value) === index;
1440     };
1441     
1442     
1443     function checkDictionary(value){
1444         for (i = 0; i < $scope.microServiceAttributeDictionaryDatas.length; i++) {
1445                 if ($scope.microServiceAttributeDictionaryDatas[i].name.localeCompare(value)){
1446                         return true;
1447                 }
1448         }
1449         
1450     }
1451     $scope.savePolicy = function(policy){
1452         if(policy.itemContent != undefined){
1453                 $scope.refreshCheck = true; 
1454                 $scope.policyNavigator = policy.itemContent;
1455                 policy.itemContent = "";
1456         }
1457         $scope.savebutton = false;
1458         var splitAt = '*';
1459         var dot ='.';
1460         var jsonPolicy = {};
1461         if(plainAttributeKeys != null){
1462                 for(a = 0; a < plainAttributeKeys.length; a++){
1463                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
1464                         console.log("splitPlainAttributeKey: " + splitPlainAttributeKey);       
1465                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
1466                         var key = splitPlainAttributeKey[0];
1467                 if(searchElement == null){
1468                     searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1469                     key = splitPlainAttributeKey[0]+'@0';
1470                 }else if (searchElement.nodeName == 'BUTTON'){
1471                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1472                                 key = splitPlainAttributeKey[0]+'@0';
1473                         }
1474                         if(searchElement != null){
1475                                 var keySplit = key.split(dot);
1476                                 var elumentLocation = keySplit.length;
1477                                 var enumKey = key;
1478                                 if (elumentLocation > 1){
1479                                         enumKey = keySplit[keySplit.length - 1];
1480                                 }
1481                                 //check it is undefined or not
1482                                 if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
1483                                                 if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
1484                                                         var multiSlect = [];
1485                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
1486                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
1487                                                                 }
1488                                                         jsonPolicy[key]= multiSlect;
1489                                                 }else{
1490                                                         console.log(" searchElement.value = > " + searchElement.value);
1491                                                         if(splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1] == "boolean"){
1492                                                                 jsonPolicy[key]= false;
1493                                                                 for(var i=0; i<booleanTrueElements.length; i++){                                                                        
1494                                                                         if(booleanTrueElements[i] == key){
1495                                                                                 jsonPolicy[key]= true;
1496                                                                         }
1497                                                                 }
1498
1499                                                         }else{
1500                                                                 jsonPolicy[key]= searchElement.value;
1501                                                         }
1502                                                 }
1503                                 } else {
1504                                         if(searchElement.value != null){
1505                                                 jsonPolicy[key]= searchElement.value;                                           
1506                                                         console.log(" searchElement.value = > " + searchElement.value);
1507                                                         if(splitPlainAttributeKey[1] == "boolean"){
1508                                                                 jsonPolicy[key]= false;
1509                                                                 for(var i=0; i<booleanTrueElements.length; i++){                                                                        
1510                                                                         if(booleanTrueElements[i] == key){
1511                                                                                 jsonPolicy[key]= true;
1512                                                                         }
1513                                                                 }
1514                                                         }
1515                                         }
1516                                 }
1517                         }
1518                 }
1519         }
1520         var uuu = "policycreation/save_policy";
1521         var postData={policyData: policy, policyJSON : jsonPolicy};
1522         $.ajax({
1523             type : 'POST',
1524             url : uuu,
1525             dataType: 'json',
1526             contentType: 'application/json',
1527             data: JSON.stringify(postData),
1528             success : function(data){
1529                 $scope.$apply(function(){
1530                         $scope.data=data.policyData;
1531                         if($scope.data == 'success'){
1532                                 $scope.temp.policy.readOnly = 'true';
1533                                 $scope.safetyChecker = data.policyData.split("#")[2];
1534                                 if ($scope.safetyChecker!=undefined) {
1535                                         Notification.success($scope.safetyChecker);
1536                                 }
1537                                 $scope.pushStatus=data.policyData.split("&")[1];
1538                                 if($scope.pushStatus=="successPush"){
1539                                         Notification.success("Policy pushed successfully");
1540                                 }
1541                                 Notification.success("Policy Saved Successfully.");     
1542                         }else if ($scope.data == 'PolicyExists'){
1543                                                 $scope.savebutton = true;
1544                                                 Notification.error("Policy Already Exists with Same Name in Scope.");
1545                                         }
1546                 });
1547                 console.log($scope.data);
1548             },
1549             error : function(data){
1550                 Notification.error("Error Occured while saving Policy.");
1551             }
1552         });
1553     };
1554     
1555     var booleanTrueElements = [];
1556     $scope.validatePolicy = function(policy){
1557         document.getElementById("validate").innerHTML = "";
1558         var splitAt = '*';
1559         var dot ='.';
1560         var jsonPolicy = {};
1561         if(plainAttributeKeys != null){
1562                 for(a = 0; a < plainAttributeKeys.length; a++){
1563                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
1564                         console.log(splitPlainAttributeKey[1]); 
1565                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
1566                         var key = splitPlainAttributeKey[0];
1567                         if(searchElement == null){
1568                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1569                                 key = splitPlainAttributeKey[0]+'@0';
1570                         }else if (searchElement.nodeName == 'BUTTON'){
1571                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1572                                 key = splitPlainAttributeKey[0]+'@0';
1573                         }
1574                         if(searchElement != null){
1575                                 if (enumKeyList.indexOf(key) != -1){
1576                                                 if (splitPlainAttributeKey[1].indexOf("true") !== -1){
1577                                                         var multiSlect = [];
1578                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
1579                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
1580                                                                 }
1581                                                         jsonPolicy[key]= multiSlect;
1582                                                 }else{
1583                                                         jsonPolicy[key]= searchElement.value;
1584                                                 }
1585                                         if(searchElement.getAttribute("required")){
1586                                                 if(!searchElement.value){
1587                                                         return;
1588                                                 }
1589                                         } 
1590                                 } else {
1591                                         if(searchElement.value != null){
1592                                                 jsonPolicy[key]= searchElement.value;
1593                                                 if(searchElement.getAttribute("required")){
1594                                                         if(!searchElement.value){
1595                                                                 return;
1596                                                         }
1597                                                 }                                               
1598                                         }
1599                                 }
1600                         }
1601                 }
1602                 
1603                 
1604                 var checkedValue = $('.onoffswitch-checkbox:checked').val();
1605                 
1606             var x = document.getElementsByClassName("onoffswitch-checkbox");
1607             
1608                              
1609                 if(checkedValue){
1610                         console.log("checkedValue:" + checkedValue);
1611                         for(var i=0; i<x.length; x++){
1612                        console.log("checkbox id: " + x[i].id);
1613                            booleanTrueElements.push(x[i].id)
1614                         }    
1615                 }
1616         }
1617         var uuu = "policyController/validate_policy.htm";
1618
1619         console.log("$scope.isCheck:" + $scope.isCheck);
1620         
1621         if($scope.isCheck == true){
1622                 if(("configName" in policy) == false){
1623                                 Notification.error("Validation Failed: configName is required");
1624                                 $scope.savebutton = true;
1625                                 return;
1626                 }
1627                 if(("location" in policy) == false){
1628                                 Notification.error("Validation Failed: location is required");
1629                                 $scope.savebutton = true;
1630                                 return;
1631                 }
1632                 if(("uuid" in policy) == false){
1633                                 Notification.error("Validation Failed: uuid is required");
1634                                 $scope.savebutton = true;
1635                                 return;
1636                 }
1637                 if(("policyScope" in policy) == false){
1638                                 Notification.error("Validation Failed: policyScope is required");
1639                                 $scope.savebutton = true;
1640                                 return;
1641                 }
1642         }        
1643         
1644         var postData={policyData: policy, policyJSON : jsonPolicy};
1645                 $.ajax({
1646                         type : 'POST',
1647                         url : uuu,
1648                         dataType: 'json',
1649                         contentType: 'application/json',
1650                         data: JSON.stringify(postData),
1651                         success : function(data){
1652                                 $scope.$apply(function(){
1653                                         $scope.validateData = data.data.replace(/\"/g, "");
1654                                         $scope.data=data.data.substring(1,8);
1655                                                 var size = data.data.length;
1656                                                 if($scope.data == 'success'){
1657                                                         Notification.success("Validation Success.");
1658                                                         $scope.savebutton = false;
1659                                                         if (size > 18){
1660                                                                 var displayWarning = data.data.substring(19,size  - 1);
1661                                                                 document.getElementById("validate").innerHTML = "Safe Policy Warning Message  :  "+displayWarning;
1662                                                                 document.getElementById("validate").style.color = "white";
1663                                                                 document.getElementById("validate").style.backgroundColor = "skyblue";
1664                                                         }
1665                                                 }else{
1666                                                         Notification.error("Validation Failed.");
1667                                                         document.getElementById("validate").innerHTML = $scope.validateData;
1668                                                         document.getElementById("validate").style.color = "white";
1669                                                         document.getElementById("validate").style.backgroundColor = "red";
1670                                                         $scope.savebutton = true;
1671                                                 }
1672                                                 
1673                                 });
1674                                 console.log($scope.data);       
1675                         },
1676                         error : function(data){
1677                                 Notification.error("Validation Failed.");
1678                                 $scope.savebutton = true;
1679                         }
1680                 });
1681     };
1682
1683     function extend(obj, src) {
1684         for (var key in src) {
1685             if (src.hasOwnProperty(key)) obj[key] = src[key];
1686         }
1687         return obj;
1688     }
1689     
1690         // Switch Click
1691         $('.Switch').click(function() {
1692                         // Check If Enabled (Has 'On' Class)
1693                         if ($(this).hasClass('On')){
1694                                 // Try To Find Checkbox Within Parent Div, And Check It
1695                                 $(this).parent().find('input:checkbox').attr('checked', true);
1696                                 // Change Button Style - Remove On Class, Add Off Class
1697                                 $(this).removeClass('On').addClass('Off');
1698                         } else { // If Button Is Disabled (Has 'Off' Class)
1699                                 // Try To Find Checkbox Within Parent Div, And Uncheck It
1700                                 $(this).parent().find('input:checkbox').attr('checked', false); 
1701                                 // Change Button Style - Remove Off Class, Add On Class
1702                                 $(this).removeClass('Off').addClass('On');      
1703                         }       
1704                 });
1705          // Loops Through Each Toggle Switch On Page
1706         $('.Switch').each(function() {
1707                         // Search of a checkbox within the parent
1708                         if ($(this).parent().find('input:checkbox').length){
1709                                 
1710                                 // If checkbox doesnt have the show class then hide it
1711                                 if (!$(this).parent().find('input:checkbox').hasClass("show")){
1712                                         $(this).parent().find('input:checkbox').hide(); }
1713                         
1714                                 // Look at the checkbox's checkked state
1715                                 if ($(this).parent().find('input:checkbox').is(':checked')){
1716                                         // Checkbox is not checked, Remove the On Class and Add the Off Class
1717                                         $(this).removeClass('On').addClass('Off');
1718                                 } else {                        
1719                                         // Checkbox Is Checked Remove Off Class, and Add the On Class
1720                                         $(this).removeClass('Off').addClass('On');
1721                                 }
1722                         }
1723                 });
1724
1725 }]);