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