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