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