Fix issue with rendering 'identity' key in GUI
[policy/engine.git] / POLICY-SDK-APP / src / main / webapp / app / policyApp / policy-models / Editor / PolicyTemplateController / OptimizationPolicyController.js
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 angular.module('abs').controller('optimizationController', ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
21     $("#dialog").hide();
22     
23     $scope.policyNavigator;
24     $scope.isCheck = false;
25     $scope.savebutton = true;
26     $scope.refreshCheck = false;
27     
28     if(!$scope.temp.policy.editPolicy  && !$scope.temp.policy.readOnly){
29         $scope.temp.policy = {
30                         policyType : "Config",
31                         configPolicyType : "Optimization"
32         }
33     };
34     
35     $scope.refresh = function(){
36         if($scope.refreshCheck){
37                 $scope.policyNavigator.refresh();
38         }
39         $scope.modal('createNewPolicy', true);
40         $scope.temp.policy = "";
41     };
42     
43     $scope.modal = function(id, hide) {
44         return $('#' + id).modal(hide ? 'hide' : 'show');
45     };
46     
47     $('#ttlDate').datepicker({
48         dateFormat: 'dd/mm/yy',
49         changeMonth: true,
50         changeYear: true,
51         onSelect: function(date) {
52                 angular.element($('#ttlDate')).triggerHandler('input');
53         }
54     });
55     
56         if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly  != undefined){
57                 if ($scope.temp.policy.configName == undefined){
58                         $scope.isCheck = false;
59                 }else{
60                         $scope.isCheck = true;
61                 }
62         }else {
63                 $scope.isCheck = false;
64         }
65                 
66         PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
67                 var j = data;
68                 $scope.data = JSON.parse(j.data);
69                 console.log($scope.data);
70                 $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
71                 console.log($scope.onapNameDictionaryDatas);
72         }, function (error) {
73                 console.log("failed");
74         });
75
76         PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
77                 var j = data;
78                 $scope.data = JSON.parse(j.data);
79                 console.log($scope.data);
80                 $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
81                 console.log($scope.priorityDatas);
82         }, function (error) {
83                 console.log("failed");
84         });
85
86         PolicyAppService.getData('getDictionary/get_OptimizationModelsDataByName').then(function (data) {
87                 var j = data;
88                 $scope.data = JSON.parse(j.data);
89                 console.log($scope.data);
90                 var inputModelList = JSON.parse($scope.data.optimizationModelsDictionaryDatas);
91                 var unique = {};
92                 var uniqueList = [];
93                 for(var i = 0; i < inputModelList.length; i++){
94                         if(typeof unique[inputModelList[i]] == "undefined"){
95                                 unique[inputModelList[i]] = "";
96                                 uniqueList.push(inputModelList[i]);
97                         }
98                 }
99                 $scope.optimizationModelsDictionaryDatas = uniqueList;
100                 console.log($scope.optimizationModelsDictionaryDatas);
101         }, function (error) {
102                 console.log("failed");
103         });
104
105         PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
106                 var j = data;
107                 $scope.data = JSON.parse(j.data);
108                 console.log($scope.data);
109                 $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
110                 console.log($scope.riskTypeDictionaryDatas);
111         }, function (error) {
112                 console.log("failed");
113         });
114
115          $scope.choices = [];
116          $scope.attributeDatas = [{"attributes" : $scope.choices}];
117          $scope.isInitEditTemplate = true;  //just initially create the edit template, didn't click add button yet.
118          $scope.addNewChoice = function(value) {
119                  console.log("input value : " + value);
120                  if(value != undefined){
121                         if (value.startsWith('div.')){
122                                 value = value.replace('div.','');
123                         }
124                         var parentElement = document.getElementById("div."+value);
125                         var div = document.getElementById(value+"@0");
126                         if(div != null){
127                                 var clone = div.cloneNode(true); 
128                                 var addElement = parentElement.childElementCount;
129                                 clone.id = ''+value+'@'+addElement;
130                                 clone.value = '';
131                                 if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ //if it's view or edit
132                                         if($scope.temp.policy.ruleData[clone.id] || ($scope.temp.policy.editPolicy && !$scope.isInitEditTemplate)){  // Only append child if its value found in ruleData or edit mode
133                                                 if($scope.temp.policy.ruleData[clone.id]){
134                                                     clone.value = $scope.temp.policy.ruleData[clone.id];
135                                                 }
136                                                 if(!clone.className.includes("child_single")){   
137                                                         clone.className += ' child_single'; //single element clone
138                                                 }
139                                                 document.getElementById("div."+value).appendChild(clone);
140                                                 plainAttributeKeys.push(''+value+'@'+addElement);
141                                         }
142                                 }else{ //not view or edit
143                                         if(!clone.className.includes("child_single")){   
144                                                 clone.className += ' child_single'; //single element clone
145                                         }
146                                         document.getElementById("div."+value).appendChild(clone);
147                                         plainAttributeKeys.push(''+value+'@'+addElement);
148                                 }
149                         }else{
150                                 div = document.getElementById("div."+value+"@0");
151                                 
152                                 if(div){
153                                 div.className += ' children_group'; //div with a group of children.
154                                 }                               
155                                 var childElement = parentElement.firstElementChild;
156                                 var countParent = parentElement.childElementCount;
157                                 var childElementString = childElement.innerHTML;
158                                 var find = value+"@0";
159                                 var re = new RegExp(find, 'g');
160                                 childElementString = childElementString.replace(re,value+'@' + countParent);
161                                 var clone = childElement.cloneNode(true);
162                                 for (var ii = 0; ii < parentElement.childNodes.length; ii++){
163                             var childId = parentElement.childNodes[ii].id;
164                             if(ii = parentElement.childNodes.length){
165                                 var childnewId = childId.slice(0, -1);
166                                 var count = childId.slice(-1);
167                             }
168                         }
169                                 var countvalue = parseInt(count) + 1;
170                                 clone.id = childnewId+countvalue;
171                                 clone.value = '';
172                                 clone.innerHTML=childElementString;
173                                 document.getElementById("div."+value).appendChild(clone);
174                                 var selects = clone.getElementsByTagName("select");
175                                 var inputs = clone.getElementsByTagName("input");
176                                 var removeValues = [];
177                                 for(var i=0; i<inputs.length; i++){
178                                         if ($scope.temp.policy.ruleData!=undefined){
179                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
180                                                 if (checkValue!=undefined && checkValue != "undefined"){
181                                                         if($scope.temp.policy.ruleData != null){
182                                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
183                                                                 document.getElementById(inputs[i].id).value = $scope.temp.policy.ruleData[inputs[i].id];
184                                                                 plainAttributeKeys.push(inputs[i].id);
185                                                         }
186                                                 } else {
187                                                         plainAttributeKeys.push(inputs[i].id);
188                                                 }
189                                         }else {
190                                                 plainAttributeKeys.push(inputs[i].id);
191                                         }
192                                 }
193                                 
194                                 for(var i=0; i<selects.length; i++){
195                                         if ($scope.temp.policy.ruleData!=undefined){
196                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
197                                                 if (checkValue!=undefined && checkValue!="undefined"){
198                                                         if($scope.temp.policy.ruleData != null){
199                                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
200                                                                 document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
201                                                                 plainAttributeKeys.push(selects[i].id);
202                                                         }
203                                                 } else {
204                                                         plainAttributeKeys.push(selects[i].id);
205                                                 }
206                                         }else {
207                                                 plainAttributeKeys.push(selects[i].id);
208                                         }
209                                 }
210                                 
211                                 for (var k=0; k<removeValues.length; k++){
212                                         var elem = document.getElementById(removeValues[k]);
213                                         elem.parentNode.removeChild(elem);
214                                 }
215                                 var ele = angular.element(document.getElementById("div."+value));
216                         $compile(ele.contents())($scope);
217                     $scope.$apply();
218                         }
219                  }
220          };
221          
222          function findVal(object, key) {
223                     var value;
224                     Object.keys(object).some(function(k) {
225                         if (k === key) {
226                             value = object[k];
227                             return true;
228                         }
229                         if (object[k] && typeof object[k] === 'object') {
230                             value = findVal(object[k], key);
231                             return value !== undefined;
232                         }
233                     });
234                     return value;
235         }
236          
237          $scope.removeChoice = function(value) {
238                  console.log(value);
239                  if(value != undefined){
240                          var c = document.getElementById("div."+value).childElementCount;
241                          
242                          if(c == 1){
243                                  Notification.error("The original one is not removable.");
244                                  return;
245                          }      
246                          document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);     
247                  }
248          };
249          
250          $scope.pullVersion = function(serviceName) {
251                  console.log(serviceName);
252                  if(serviceName != undefined){
253                          var uuu = "policyController/getModelServiceVersionData.htm";
254                          var postData={policyData: serviceName};
255                          $.ajax({
256                                  type : 'POST',
257                                  url : uuu,
258                                  dataType: 'json',
259                                  contentType: 'application/json',
260                                  data: JSON.stringify(postData),
261                                  success : function(data){
262                                          $scope.$apply(function(){
263                                                  $scope.optimizationModelsDictionaryVersionDatas = data[0].optimizationModelVersionData;
264                                          });
265                                  },
266                                  error : function(data){
267                                          alert("Error While Retrieving the Template Layout Pattern.");
268                                  }
269                          });             
270                  }
271          };
272     
273     var splitDash = '-';
274         var splitEqual = '=';
275         var splitComma = ',';
276         var splitcolon = ':';
277         var splitsemicolon = ";";
278         var splitEnum = "],";
279         var plainAttributeKeys = [];
280         var matching = [];
281         var enumKeyList = [];
282         var dictionaryList = [];
283         var dictionaryNameList = [];
284     $scope.addDataToFields = function(serviceName, version){
285         if(serviceName != null && version !=null){
286                 var service=serviceName+"-v"+version;
287                 var myNode = document.getElementById("DynamicTemplate");
288                 myNode.innerHTML = '';
289             var uuu = "policyController/getOptimizationTemplateData.htm";
290             var postData={policyData: service};
291             var dataOrderInfo = "";
292             
293             $.ajax({
294                 type : 'POST',
295                 url : uuu,
296                 dataType: 'json',
297                 contentType: 'application/json',
298                 data: JSON.stringify(postData),
299                 success : function(data){
300                     $scope.$apply(function(){
301                         var plainAttributeKeys = [];
302                         $scope.optimizationModelData = data[0].optimizationModelData;
303                         $scope.optimizationJsonDate = data[0].jsonValue;
304                         $scope.dataOrderInfo = null;
305                         $scope.dataOrderInfo = data[0].dataOrderInfo;
306                         console.log("data[0].dataOrderInfo: " + data[0].dataOrderInfo);
307                         console.log("$scope.dataOrderInfo: " + $scope.dataOrderInfo);   
308                         if(data[0].allManyTrueKeys){
309                                 console.log("$scope.allManyTrueKeys: " + $scope.allManyTrueKeys);
310                         }
311                         console.log("$scope.optimizationJsonDate: " + $scope.optimizationJsonDate);     
312                         var attributes = $scope.optimizationModelData.attributes;
313                         var refAttributes = $scope.optimizationModelData.ref_attributes;
314                         var subAttributes =     $scope.optimizationModelData.sub_attributes;   
315                         console.log("attributes: " +attributes);                        
316                         console.log("subAttributes: " + subAttributes); 
317                         console.log("refAttributes: " + refAttributes); 
318                         
319                         var headDefautlsData  = data[0].headDefautlsData;
320                         if(headDefautlsData != null){
321                                          $scope.temp.policy.onapName = headDefautlsData.onapName;
322                                          $scope.temp.policy.guard = headDefautlsData.guard;
323                                          $scope.temp.policy.riskType = headDefautlsData.riskType;
324                                          $scope.temp.policy.riskLevel = headDefautlsData.riskLevel;
325                                          $scope.temp.policy.priority = headDefautlsData.priority;
326                                          
327                         }else if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
328                                          $scope.temp.policy.onapName = "";
329                                          $scope.temp.policy.guard = "";
330                                          $scope.temp.policy.riskType = "";
331                                          $scope.temp.policy.riskLevel = "";
332                                          $scope.temp.policy.priority = "";
333                         }
334                         
335                         var enumAttributes = $scope.optimizationModelData.enumValues;
336                         var annotation = $scope.optimizationModelData.annotation;
337                         var dictionary = $scope.microServiceAttributeDictionaryDatas;
338
339                         if (annotation == null || annotation.length<1){
340                                 $scope.isCheck = true;
341                         }else {
342                                 $scope.isCheck = false;
343                                 var annoationList = annotation.split(splitComma);
344                                 for (k = 0; k < annoationList.length; k++){
345                                         var splitAnnotation = annoationList[k].split(splitEqual);
346                                         if (splitAnnotation[1].includes("matching-true")){
347                                                 matching.push(splitAnnotation[0].trim());
348                                         }
349                                 }
350
351                         }
352
353                         if (dictionary!= null && dictionary.length>1){
354                                 for (m=0; m < dictionary.length; m += 1){
355                                         var keyCompare = dictionary[m].name;
356                                         var valueCompare = dictionary[m].value;
357                                         var valueModel = dictionary[m].modelName;
358                                         var conpairService = serviceName;
359                                         if (valueModel.includes('-v')){
360                                                 conpairService = service;
361                                         }
362                                         if(valueModel.localeCompare(conpairService) == 0){
363                                                 console.log(valueCompare);      
364                                                 dictionaryList.push(dictionary[m]);
365                                                 if (!dictionaryNameList.includes(dictionary[m].name)){
366                                                         dictionaryNameList.push(dictionary[m].name)
367                                                 }
368                                         }
369                                 }
370                         }
371
372                                 $scope.temp.policy.ruleGridData = [];
373                                 
374                                 if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
375                                         dataOrderInfo = $scope.dataOrderInfo;
376                                 }
377                                 
378                                 $scope.jsonLayout($scope.optimizationJsonDate);
379                                 
380                     });
381                     
382                     if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){  // If it's veiw or edit
383                         
384                         if($scope.temp.policy.editPolicy){
385                                 $scope.isInitEditTemplate = true;
386                         }
387                         
388                         var checkData = [];
389                         var data = [];
390                             // If ruleData contains extra elements created by clicked add button 
391                                 if($scope.temp.policy.ruleData != null){
392                                         var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
393                                         propNames.forEach(function(name) {
394                                                 data.push(name);
395                                         });
396                                         
397                                         var extraElements = data;
398                                         
399                                         if(plainAttributeKeys != null){
400                                                 for(b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
401                                                         var newValue = plainAttributeKeys[b].split("*");
402                                                         for(a = 0; a < data.length; a++){
403                                                                 if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
404                                                                         extraElements.splice(a, 1);
405                                                                 }
406                                                         }
407                                         
408                                                 }
409                                         
410                                                 //--- Populate these extra elements created by clicked add button 
411                                                 for(a = 0; a < extraElements.length; a++){                              
412                                                         if(extraElements[a].includes("@")){
413                                                                 var index = extraElements[a].lastIndexOf("@");
414                                                                 if(index > 0){
415                                                                     // Get the number after @
416                                                                     var n = getNumOfDigits(extraElements[a], index+1);
417                                                                                         
418                                                                         var key = extraElements[a].substring(0, index+n+1); //include @x in key also by n+2 since x can be 1,12, etc
419                                                                         console.log("key: " + key);
420                                                                         checkData.push(key);
421                                                                 }
422                                                         }
423                                                 }
424                                                 var unique = checkData.filter(onlyUnique);
425                                                 //if no layout order info, keep the process as before
426                                                 if(!dataOrderInfo){
427                                                         for(i =0; i < unique.length; i++){
428                                                                 //remove @x and let addNewChoice add @1 or @2...
429                                                                 //var newKey = unique[i].substring(0, unique[i].length-2);
430                                                                 var index = unique[i].lastIndexOf("@");
431                                                                 var newKey = unique[i].substring(0, index);
432                                                                 console.log("newKey: " + newKey);       
433                                                                 $scope.addNewChoice(newKey);
434                                                         }
435                                                 }else{
436
437                                                         for (i = 0; i < $scope.labelManyKeys.length; i++) {
438                                                                 console.log("dataOrderInfo["+i+"]"+  dataOrderInfo[i]);
439                                                             var label = $scope.labelManyKeys[i];
440                                                                         // first add parent/label level
441                                                                         for (k = 0; k < unique.length; k++){
442                                                                                 var newindex = unique[k].lastIndexOf("@");
443                                                                                 var newKey = unique[k].substring(0, index);
444                                                                             if(label == newKey){
445                                                         //Check this label has bee created or not
446                                                                                 if(!document.getElementById(unique[k])){
447                                                                                         $scope.addNewChoice(newKey);
448                                                                                 }
449                                                                                 unique[k] = "*processed*";
450                                                                                         break;
451                                                                             }
452                                                                         }                                                                               
453                                                         }
454                                                         
455                                                         //---reset to default
456                                                         dataOrderInfo = [];
457                                                         $scope.labelManyKeys = [];
458                                                         
459                                                         //---process none labels
460                                                         for (j = 0; j < unique.length; j++){
461                                                                 if(unique[j] != "*processed*"){
462                                                                         // if not created yet
463                                                                         if(!document.getElementById(unique[j])){
464                                                                                 var index = unique[j].lastIndexOf("@");
465                                                                                 var newKey = unique[j].substring(0, index);
466                                                                             $scope.addNewChoice(newKey);
467                                                                         }
468                                                                 }
469                                                         }
470                                                 }
471                                     }
472                             }
473                             
474                         if($scope.temp.policy.editPolicy){
475                                 //clean all the events of addNewChoice
476                                 $scope.$on('$destroy', addNewChoice);
477                         }
478                             
479                     }
480                     var ele = angular.element(document.getElementById("DynamicTemplate"));
481                         $compile(ele.contents())($scope);
482                     $scope.$apply();
483                 },
484                 error : function(data){
485                     alert("Error While Retrieving the Template Layout Pattern.");
486                 }
487             });
488         }
489     };
490     
491     function getNumOfDigits(str_value, index){
492                 // Get the number after @
493                 var str = str_value.substring(index, str_value.length); 
494                 var c = '';
495                 var n = 0;
496                 for (var x = 0; x < str.length; x++){                                                                   
497                     c = str.charAt(x);
498                             if(!isNaN(c)){ 
499                 n++;                                                     
500                     }else{
501                 break;
502             }
503                 }
504                 return n;
505     }
506     
507     function getDictionary(attribute){
508         var dicName = attribute;
509         if(attribute){
510            if(attribute.includes(":")){
511                    dicName = attribute.split(":")[0];
512            }
513         }
514             var dictionaryRegExp = new RegExp(dicName);
515             listemunerateValues = [];
516             if (dictionaryRegExp.test(dictionaryNameList)) {
517                         for (p=0; p < dictionaryList.length; p += 1) {
518                                 if (dicName == dictionaryList[p].name) {
519                                         listemunerateValues.push(dictionaryList[p].value);
520                                 }
521                         }
522             }
523             return listemunerateValues;
524     }
525     
526     function getList(attribute) {
527         var enumName = attribute;
528         console.log("In getList: attribute => " + attribute);
529         if(attribute){
530            if(attribute.includes(":")){
531                    enumName = attribute.split(":")[0];
532            }
533         }   
534         var baseEnum = $scope.optimizationModelData.enumValues;
535         var enumList = [];
536         if(baseEnum != null){
537                 enumList = baseEnum.split(splitEnum);
538         }
539         var enumAttributes;
540         var patternTest = new RegExp(enumName);
541         for (k=0; k < enumList.length; k += 1){
542                 if(patternTest.test(enumList[k]) == true){
543                         enumAttributes = enumList[k].trim();
544                 }
545         }
546
547         if(enumAttributes){
548                 enumAttributes = enumAttributes.replace("[", "");
549                 enumAttributes = enumAttributes.replace("]", "");
550                 enumAttributes = enumAttributes.replace(/ /g, '');
551                         var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
552                         listemunerateValues  = dropListAfterCommaSplit[1].split(splitComma);
553                 return listemunerateValues;
554              }
555            
556          return [];
557     }
558             
559     function getBooleanList(){
560         var booleanList = [];
561         booleanList.push(true);
562         booleanList.push(false);
563         return booleanList;
564     }
565
566     function isArray(arrayTest) {
567         return Object.prototype.toString.call(arrayTest) === '[object Array]';
568     }
569             
570         var lableList = [];
571         
572     $scope.layOutElementList = [];
573     $scope.layOutOnlyLableList = [];
574     
575     var elementOrderNum = 0;
576             
577         function deconstructJSON(layOutData, level , name) {
578
579                  var array = false;
580                  var label = level;
581                  var stringValue = "java.lang.String";
582                  var string = "string";
583                  var intValue = "int";
584                  var integerValue = "integer";
585                  var double = "double";
586                  var boolean = "boolean";
587                  var baseLevel = level;
588                  var list = "list";
589                  var String = "String";
590                  
591                  var attributekey = "";
592                  
593                 if (name.length > 1){
594                         label = label + name + '.';
595                 }
596                 
597             for (key in layOutData) {
598                 array = isArray(layOutData[key]);
599                 console.log("key: " + key , "value: " + layOutData[key]);
600         
601                 if (!!layOutData[key] && typeof(layOutData[key])=="object") {
602                         
603                         if (array==false && key!=="0"){
604                                 
605                                 if($scope.dataOrderInfo){
606                                     var labelObject = {"label" : key, "level" : label, "array" : array};
607                                     //save it to the list
608                                     $scope.layOutOnlyLableList.push(labelObject);
609                                     
610                                 }else {
611                                         //call label layout
612                                         $scope.labelLayout(label, key, array );
613                                 }
614                                 
615                         }
616                         
617                         if (array == true && key!=0){
618                                 lableList.push(key);
619                         }
620                         
621                         if (lableList.length > 0){
622                                 array = true;
623                         }
624                         if ( key==="0"){
625                                 var newKey = lableList.pop();
626                                 
627                                 if($scope.dataOrderInfo){
628                                         
629                                         var labelObject = {"label" : newKey, "level" : baseLevel, "array" : array};
630                                         //save it to the list
631                                         $scope.layOutOnlyLableList.push(labelObject);
632                                         
633                                 }else {
634                                         //call label layout 
635                                     $scope.labelLayout(baseLevel, newKey, array );
636                                 }
637                                 
638                                 if (array){
639                                         label = baseLevel + newKey + '@0.';
640                                 } else {
641                                         label = baseLevel + newKey + '.';
642                                 }
643                         }
644                         deconstructJSON(layOutData[key] , label, key);
645                 } else {
646                         var attirbuteLabel = label;
647                         var defaultValue='';
648                         var isRequired = false;
649                         if (layOutData[key].includes('defaultValue-')){
650                                 defaultValue = layOutData[key].split('defaultValue-')[1];
651                         }
652
653                         if (key==="0"){
654                                 array = true;
655                                 attributekey = lableList.pop();
656                                 attirbuteLabel = baseLevel;
657                         } else {
658                                 attributekey = key.split();
659                         }
660                         
661                         if (layOutData[key].includes('required-true')){
662                                 isRequired = true;
663                         }
664                         
665                         var subAttributes = $scope.optimizationModelData.sub_attributes;
666                         
667                         if(subAttributes){                                      
668                                 var jsonObject = JSON.parse(subAttributes);                                     
669                                 var allkeys = Object.keys(jsonObject);
670                                 if(allkeys){
671                                         for (var k = 0; k < allkeys.length; k++) {
672                                                 var keyValue = allkeys[k];
673                                                 console.log(" keyValue:jsonObject["+keyValue+ "]: " + jsonObject[keyValue]);
674                                                 if(jsonObject[keyValue]){
675                                                         var tempObject = jsonObject[keyValue];
676                                                         if(tempObject && tempObject[key]){
677                                                         if (tempObject[key].includes('required-true')){
678                                                                 isRequired = true;
679                                                         }       
680                                                         }
681                                                 }
682                                         }                                               
683                                 }                                       
684                         }
685                         
686                         var elementObject = {};
687                         switch (layOutData[key].split(splitcolon)[0]){
688                         
689                                 case stringValue:
690                                 case string:
691                                         if($scope.dataOrderInfo){                                                       
692                                                 elementOrderNum++;
693                                                 elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"text"};
694                                                 $scope.layOutElementList.push(elementObject);
695                                         }else{
696                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
697                                         }
698                                         break;                                          
699                                 case intValue: 
700                                 case integerValue: 
701                                         if($scope.dataOrderInfo){
702                                                 elementOrderNum++;
703                                                 elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"number"};
704                                                 $scope.layOutElementList.push(elementObject);
705                                         }else{
706                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
707                                         }
708                                         break;                                          
709                                 case double:
710                                         if($scope.dataOrderInfo){
711                                                 elementOrderNum++;
712                                                 elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"double"};
713                                                 $scope.layOutElementList.push(elementObject);                                                   
714                                         }else{
715                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
716                                         }
717                                         break;
718                                 case boolean:
719                                         if($scope.dataOrderInfo){
720                                                 elementOrderNum++;
721                                                 elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key], "list": getBooleanList, "isRequired": isRequired, "type":"dropBox"};
722                                                 $scope.layOutElementList.push(elementObject);
723                                         }else{
724                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], getBooleanList());
725                                         }
726                                         break;
727                                 default:
728                                         if (layOutData[key].includes('dictionary-')){
729                                                 var list = getDictionary(layOutData[key].split('dictionary-')[1]);
730                                         }else{
731                                                 //--- get dropdown values from enumValues
732                                                 var list = getList(layOutData[key]);
733                                         }
734                                         if (list.length===0){ //not dropdown element
735                                                 if($scope.dataOrderInfo){
736                                                         elementOrderNum++;
737                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"text"};
738                                                         $scope.layOutElementList.push(elementObject);
739                                                         
740                                                 }else{
741                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
742                                                 }                                                       
743                                         }else{
744                                                 if($scope.dataOrderInfo){
745                                                         elementOrderNum++;
746                                                         elementObject = {"id": elementOrderNum, "attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key],"isRequired": isRequired, "list":list, "type":"dropBox"};
747                                                         $scope.layOutElementList.push(elementObject);                                                           
748                                                 }else{
749                                                         $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], list, isRequired);
750                                                 }
751                                         }
752                                         break;
753                         }
754                 }
755             }
756         }  
757
758     $scope.validContionalRequired = function(parentId) {
759         console.log("ng-blur event: parentId : " + parentId);
760         var c = document.getElementById(parentId).children;
761         var i;
762         var hasValue = false;
763         for (i = 0; i < c.length; i++) {
764                 if(c[i].getAttribute("data-conditional")){
765                     console.log(c[i].getAttribute("data-conditional"));
766                     console.log(c[i].value);
767                     if(c[i].value != null && c[i].value.trim() != ""){
768                         hasValue = true;
769                     }
770                 }
771         }
772
773             for (i = 0; i < c.length; i++) {
774                 if(c[i].getAttribute("data-conditional")){
775                         if(hasValue){
776                             c[i].setAttribute("required", true);
777                         }else{
778                                 c[i].removeAttribute("required");
779                         }
780                 }
781             }           
782      }
783                         
784     $scope.jsonLayout = function(layOutData){
785         
786        deconstructJSON(layOutData , "", "");
787                    
788            var orderValue = $scope.dataOrderInfo;
789            var layOutElementList = $scope.layOutElementList;
790            var labelList = $scope.layOutOnlyLableList;
791             
792            //reset to default
793            elementOrderNum = 0;
794            $scope.layOutElementList = [];
795            $scope.layOutOnlyLableList = [];
796            
797            // Only layout in order if order info provided
798            if(orderValue){
799                    
800                    if(orderValue.includes("[")){
801                           orderValue = orderValue.replace("[", "") ;
802                           orderValue = orderValue.replace("]", "") ;
803                    }
804                    
805                    orderValue = orderValue.split(',') ;
806                    
807                    for (i = 0; i < orderValue.length; i++) {
808                            console.log("orderValue["+i+"]"+  orderValue[i]);
809                            var key = orderValue[i].trim();
810                          
811                             //--- Create labels first {"label" : newKey, "level" : baseLevel, "array" : array};
812                            if(labelList){
813                                    for (k = 0; k < labelList.length; k++){
814                                            
815                                           var label = labelList[k].label.toString().trim();
816                                           var level = labelList[k].level.toString().trim();
817                                           var array = labelList[k].array;
818                                           
819                                           if(key == label){                                                       
820                                                  $scope.labelLayout(level, label, array);
821                                          //in case to have duplicate label names
822                                                  labelList[k].label = "*processed*";
823                                                  break;
824                                           }
825                                    }
826                            }
827                            //--- then layout each element based on its order defined in YAML file
828                    for (j = 0; j < layOutElementList.length; j++) { 
829                            
830                            var attributekey = layOutElementList[j].attributekey.toString().trim();                                         
831                         
832                            if(key == attributekey){     
833         
834                                    var attirbuteLabel = layOutElementList[j].attirbuteLabel.toString().trim();
835                                    var defaultValue = layOutElementList[j].defaultValue.toString().trim();
836                                    var isRequired = layOutElementList[j].isRequired;
837                                    
838                                    console.log("layOutElementList[" +j+ "]: id:" + layOutElementList[j].id + ", attributekey:"+ layOutElementList[j].attributekey + ", attirbuteLabel:" + layOutElementList[j].attirbuteLabel);
839                                   
840                                    if (layOutElementList[j].type == "dropBox"){ 
841                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, layOutElementList[j].array, defaultValue, layOutElementList[j].list, isRequired);
842                                 
843                                    }else{
844                                             $scope.attributeBox(attributekey, layOutElementList[j].array, attirbuteLabel, defaultValue, isRequired, layOutElementList[j].type); 
845         
846                                    }
847                                    
848                                    //in case to have duplicate attribute names
849                                    layOutElementList[j].attributekey = "*processed*";
850                                    break;
851                            }
852                    
853                    }
854                    
855                    }
856            }
857     }
858     
859     
860     $scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType ){
861                 $scope.temp.policy.ruleGridData.push(attibuteKey);                      
862                 var br = document.createElement("BR");
863         
864                 var label = document.createElement("Label");
865                 var labeltext = null;
866                 var requiredLabName = "";
867                 if (matching.includes(attibuteKey)){
868                         labeltext = document.createTextNode(attibuteKey + "*!");        
869                         isRequired = true;  //set required as true for matching element
870                 }else {
871                         if(isRequired){
872                                 requiredLabName = attibuteKey + " * ";
873                                 labeltext = document.createTextNode(requiredLabName);
874                         }else{
875                             labeltext = document.createTextNode(attibuteKey);   
876                         }
877                 }
878
879         
880                 var divID = labelValue;
881                 
882                 if (labelValue.length  < 1){
883                         divID = "DynamicTemplate";
884                 }else if (labelValue.endsWith('.')){
885                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
886                 }
887                 
888                 label.appendChild(labeltext);
889                 
890                 var textField = document.createElement("INPUT");
891                 
892                 textField.setAttribute("class" , "form-control");
893                 if(dataType){
894                            if(dataType == "double"){
895                                    textField.setAttribute("type" , "number");
896                                    textField.setAttribute("step" , "any");
897                            }else{
898                               textField.setAttribute("type" , dataType);
899                            }
900                 }
901                 textField.setAttribute("style" , "width:300px;");
902                 textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
903                 var checkKey;
904                 var id = "";
905                 if(attributeManyKey){
906                         checkKey = labelValue + attibuteKey+'@0';
907                         textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+''); 
908                         var divTag = document.createElement("div");
909                         divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
910                         var addButton = document.createElement("BUTTON");
911                         var buttonaddLabel = document.createTextNode("+");       
912                         addButton.appendChild(buttonaddLabel); 
913                         addButton.setAttribute("id", labelValue + attibuteKey);
914                         addButton.setAttribute("class", "btn btn-add-remove");
915                         addButton.setAttribute("ng-click" ,  'addNewChoice("'+labelValue + attibuteKey+'");');
916                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
917                         var removeButton = document.createElement("BUTTON");
918                         var buttonremoveLabel = document.createTextNode("-");       
919                         removeButton.appendChild(buttonremoveLabel); 
920                         removeButton.setAttribute("class", "btn btn-add-remove");
921                         removeButton.setAttribute("ng-click" ,  'removeChoice("'+labelValue + attibuteKey+'");');
922                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
923                         document.getElementById(divID).appendChild(addButton); 
924                         document.getElementById(divID).appendChild(removeButton); 
925                         document.getElementById(divID).appendChild(label); 
926                         id = "div."+labelValue+attibuteKey;
927                         divTag.setAttribute("id", id); 
928                         document.getElementById(divID).appendChild(divTag);
929                         textField.className += ' first_child';  
930                         if(isRequired){
931                                 textField.setAttribute("required", "true");
932                         }                       
933                         divTag.appendChild(textField);                  
934                         document.getElementById(divID).appendChild(divTag); 
935                         
936                 }else{
937                         checkKey = labelValue + attibuteKey;
938                         textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
939                         if(document.getElementById(divID).hasAttribute('required') || !document.getElementById(divID).hasAttribute('data-conditional')){
940                                 if(requiredLabName.includes("*") || isRequired){
941                                         textField.setAttribute("required", "true");
942                                 }
943                         }else if (document.getElementById(divID).hasAttribute('data-conditional')){
944                                 if(requiredLabName.includes("*")){                                      
945                                         var requiredNode = document.createElement('span');
946                                         requiredNode.setAttribute("class", "mstooltip");
947                                         requiredNode.textContent = "?";
948                                         label.appendChild(requiredNode);
949                                         
950                                         var requiredNodeToolTip = document.createElement('span');
951                                         requiredNodeToolTip.setAttribute("class", "tooltiptext");
952                                         requiredNodeToolTip.textContent = "Conditional Required";
953                                         requiredNode.appendChild(requiredNodeToolTip);
954                                         
955                                         textField.setAttribute("data-conditional", divID);
956                                         textField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
957                                 }
958                         }
959                 
960                         document.getElementById(divID).appendChild(label);  
961                         document.getElementById(divID).appendChild(textField);  
962                         document.getElementById(divID).appendChild(br); 
963         
964                 }
965
966                 if(divID.includes("@0") && divID.includes("div.")){
967                         var firstChild_Id = divID.split("@0")[0];
968                         var firstChild_element = document.getElementById(firstChild_Id);
969                         if(firstChild_element){
970                                 firstChild_element.className += ' children_group';  //here is a div with a group of children.
971                         }
972                 }
973                 console.log('firstChild_Id: ' + firstChild_Id);
974                 console.log('divID: ' + divID);
975                 
976                 if (defaultValue.length > 0){   
977                         if(defaultValue.includes(":")){
978                                 defaultValue = defaultValue.split(":")[0];
979                                 if(defaultValue === "NA") {
980                                         defaultValue = "";
981                                 }                               
982                         }
983                         if(defaultValue != "undefined" && defaultValue != undefined && defaultValue != "null"){
984                         document.getElementById(checkKey).value = defaultValue;
985                         }
986                 }
987                 
988                 if($scope.temp.policy.ruleData != null){
989                         if (attributeManyKey){
990                                 var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
991                                 if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
992                                     document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
993                                 }
994                         }else{
995                                 if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
996                                     document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
997                                 }
998                         }
999                 } 
1000                 plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey); 
1001
1002     };
1003     
1004     $scope.labelManyKeys = [];
1005     $scope.labelLayout = function(labelValue, lableName, labelManyKey ){
1006                 var label = document.createElement("Label")
1007                 var divID = labelValue;
1008                 if (labelValue.endsWith('.')){
1009                         var workingLabel = labelValue.substring(0, labelValue.length-1);
1010                 }else {
1011                         var workingLabel = labelValue;
1012                 }
1013                 
1014                 if (labelValue.length  < 1){
1015                         divID = "DynamicTemplate";
1016                 } else if (labelValue.endsWith('.')){
1017                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
1018                 }
1019                 
1020                 var subAttributes = $scope.optimizationModelData.subattributes;
1021             var jsonObject = JSON.parse(subAttributes); 
1022             var lablInfo = findVal(jsonObject, lableName);
1023                 console.log("findValue : " + lableName +": "+ lablInfo);
1024                 var star = "";
1025                 var required = null;
1026                 if(lablInfo){
1027                         if(lablInfo.includes("required-true")){
1028                                 star = " *";
1029                                 required = true;
1030                         }else if (lablInfo.includes("required-false")){
1031                                 required = false
1032                         }
1033                 }
1034                 
1035                 var labeltext = document.createTextNode(lableName + star);
1036         
1037                 label.appendChild(labeltext);
1038
1039
1040                 if(labelManyKey){
1041                         var addButton = document.createElement("BUTTON");
1042                         var buttonLabel = document.createTextNode("+");       
1043                         addButton.appendChild(buttonLabel); 
1044                         addButton.setAttribute("class", "btn btn-add-remove");
1045                         addButton.setAttribute("ng-click" ,  'addNewChoice("'+labelValue + lableName+'");');
1046                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
1047                         var removeButton = document.createElement("BUTTON");
1048                         var buttonremoveLabel = document.createTextNode("-");       
1049                         removeButton.appendChild(buttonremoveLabel); 
1050                         removeButton.setAttribute("class", "btn btn-add-remove");
1051                         removeButton.setAttribute("ng-click" ,  'removeChoice("'+labelValue +lableName+'");');
1052                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly"); 
1053                         document.getElementById(divID).appendChild(addButton); 
1054                         document.getElementById(divID).appendChild(removeButton);
1055                         document.getElementById(divID).appendChild(label);
1056                         var id = "div."+labelValue+lableName;
1057                         var divTag = document.createElement("div");
1058                         divTag.setAttribute("id", id); 
1059                         document.getElementById(divID).appendChild(divTag);
1060                         
1061                         var divTag = document.createElement("div");
1062                         divTag.setAttribute("id", id +'@0');  
1063                         
1064                         divTag.className += ' children_group'; //here is div with a group of children.
1065                         
1066                         if(required){
1067                            divTag.setAttribute("required", required);  
1068                         }else if(required == false){
1069                            divTag.setAttribute("data-conditional", "yes");  
1070                         }
1071                         
1072                         document.getElementById(id).appendChild(divTag);
1073                         
1074                         $scope.labelManyKeys.push(lableName);
1075                         
1076                 }else{
1077                         var divTag = document.createElement("div");
1078                         divTag.setAttribute("id", "div."+labelValue+lableName);
1079                         divTag.className += ' children_group'; //here is div with a group of children.
1080                         if(required){
1081                             divTag.setAttribute("required", required);  
1082                         }else if(required == false){
1083                                 divTag.setAttribute("data-conditional", "yes");  
1084                         }  
1085                         document.getElementById(divID).appendChild(label);  
1086                         document.getElementById(divID).appendChild(divTag);                     
1087                 }
1088     };
1089
1090     $scope.dropBoxLayout = function(labelLevel, attributeName, many , refValue, listemunerateValues, isRequired){
1091                 var br = document.createElement("BR");
1092         
1093                 if (labelLevel.length  < 1){
1094                                 var divID = "DynamicTemplate";
1095                 } else if (labelLevel.endsWith('.')){
1096                                 var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
1097                 }       
1098         
1099         
1100                 var label = document.createElement("Label")
1101                 
1102                 var refAttributes = $scope.optimizationModelData.ref_attributes;
1103                 if(isRequired != true && refAttributes){ //check refAttributes also             
1104                                 var refAttributesList = refAttributes.split(splitComma);
1105                                 for (k = 0; k < refAttributesList.length; k++){
1106                                 var refAttribute = refAttributesList[k].split(splitEqual);                      
1107                                 if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
1108                                         isRequired = true;
1109                                 }
1110                                 }
1111                 }
1112                 
1113                 if (matching.includes(attributeName)){
1114                         var labeltext = document.createTextNode(attributeName + "*!");
1115                         label.appendChild(labeltext);
1116                         isRequired = true;  //set required as true for matching element
1117                 }else {
1118                         var labeltext = document.createTextNode(attributeName);         
1119                         if(isRequired){
1120                             var requiredLabName = attributeName+ " * ";
1121                                 labeltext = document.createTextNode(requiredLabName);
1122                         }else{
1123                             labeltext = document.createTextNode(attributeName); 
1124                         }
1125                 
1126                     label.appendChild(labeltext);               
1127                 }
1128                 label.appendChild(labeltext);
1129                 // if this field is required, but its parent is not required
1130                 if(isRequired && document.getElementById(divID).hasAttribute('data-conditional')){
1131                         var requiredNode = document.createElement('span');
1132                         requiredNode.setAttribute("class", "mstooltip");
1133                         requiredNode.textContent = "?";
1134                         label.appendChild(requiredNode);
1135                                 
1136                         var requiredNodeToolTip = document.createElement('span');
1137                         requiredNodeToolTip.setAttribute("class", "tooltiptext");
1138                         requiredNodeToolTip.textContent = "Conditional Required";
1139                         requiredNode.appendChild(requiredNodeToolTip);
1140
1141                 }
1142         
1143                 var listField = document.createElement("SELECT");
1144                 listField.setAttribute("class" , "form-control");
1145                 listField.setAttribute("style" , "width:300px;");
1146                 listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
1147                 
1148                 if(isRequired){
1149                     if(document.getElementById(divID).hasAttribute('data-conditional')){
1150                         listField.setAttribute("data-conditional", divID);
1151                         listField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
1152                     }else{
1153                                 listField.setAttribute("required", true);
1154                     }
1155                 }
1156                 if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
1157                         var optionFirst = document.createElement('option');
1158                         optionFirst.setAttribute('value', "");
1159                         listField.appendChild(optionFirst);     
1160                 }
1161                 
1162                 for (var i=0; i < listemunerateValues.length; i += 1) {
1163                         if(typeof listemunerateValues[i] == "string" && listemunerateValues[i].includes("equal-sign")){
1164                                 listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
1165                         }
1166                     var option = document.createElement('option');
1167                     option.setAttribute('value', listemunerateValues[i]);
1168                     option.appendChild(document.createTextNode(listemunerateValues[i]));
1169                     option.setAttribute('value', listemunerateValues[i]);
1170                     listField.appendChild(option);
1171                 }
1172                 listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
1173                 
1174                 enumKeyList.push(attributeName);
1175                 
1176                 document.getElementById(divID).appendChild(label);  
1177                 document.getElementById(divID).appendChild(br); 
1178                                 
1179                 if(many == true){
1180                         document.getElementById(divID).appendChild(listField).multiple = true;
1181                         plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
1182                 }else {
1183                         document.getElementById(divID).appendChild(listField).multiple = false;
1184                         plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
1185                 }
1186         
1187                 if($scope.temp.policy.ruleData != null){
1188                         if (many == true){
1189                                 document.getElementById(labelLevel +attributeName).options[0].selected = false;
1190                                 for (i=0; i < listemunerateValues.length; i += 1) {
1191                                         var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
1192                                         if (testValue === undefined){
1193                                                 testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
1194                                                 }
1195                                         var location = listemunerateValues.indexOf(testValue);
1196                                         if (location!=-1){
1197                                                 document.getElementById(labelLevel +attributeName).options[location].selected = true;
1198                                                 }
1199                                         }                       
1200                                 }else {
1201                                             if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
1202                                     document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];        
1203                                             }
1204                                 }
1205                         }
1206             };
1207     
1208     function onlyUnique(value, index, self) { 
1209         return self.indexOf(value) === index;
1210     };
1211     
1212     $scope.savePolicy = function(policy){
1213         if(policy.itemContent != undefined){
1214                 $scope.refreshCheck = true; 
1215                 $scope.policyNavigator = policy.itemContent;
1216                 policy.itemContent = "";
1217         }
1218         $scope.savebutton = false;
1219         var splitAt = '*';
1220         var dot ='.';
1221         var jsonPolicy = {};
1222         if(plainAttributeKeys != null){
1223                 for(a = 0; a < plainAttributeKeys.length; a++){
1224                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
1225                         console.log("splitPlainAttributeKey: " + splitPlainAttributeKey);       
1226                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
1227                         var key = splitPlainAttributeKey[0];
1228                         
1229                 if(searchElement == null || searchElement.nodeName == 'BUTTON'){
1230                     searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1231                     key = splitPlainAttributeKey[0]+'@0';
1232                 }
1233                 
1234                         if(searchElement != null){
1235                                 var keySplit = key.split(dot);
1236                                 var elumentLocation = keySplit.length;
1237                                 var enumKey = key;
1238                                 if (elumentLocation > 1){
1239                                         enumKey = keySplit[keySplit.length - 1];
1240                                 }
1241                                 //check it is undefined or not
1242                                 if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
1243                                                 if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
1244                                                         var multiSlect = [];
1245                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
1246                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
1247                                                                 }
1248                                                         jsonPolicy[key]= multiSlect;
1249                                                 }else{
1250                                                         console.log(" searchElement.value = > " + searchElement.value);
1251                                                         jsonPolicy[key]= searchElement.value;
1252                                                 }
1253                                 } else {
1254                                         if(searchElement.value != null){
1255                                                         console.log(" searchElement.value = > " + searchElement.value);
1256                                                 jsonPolicy[key]= searchElement.value;
1257                                         }
1258                                 }
1259                         }
1260                 }
1261         }
1262         var uuu = "policycreation/save_policy";
1263         var postData={policyData: policy, policyJSON : jsonPolicy};
1264         $.ajax({
1265             type : 'POST',
1266             url : uuu,
1267             dataType: 'json',
1268             contentType: 'application/json',
1269             data: JSON.stringify(postData),
1270             success : function(data){
1271                 $scope.$apply(function(){
1272                         $scope.data=data.policyData;
1273                         if($scope.data == 'success'){
1274                                 $scope.temp.policy.readOnly = 'true';
1275                                 $scope.safetyChecker = data.policyData.split("#")[2];
1276                                 if ($scope.safetyChecker!=undefined) {
1277                                         Notification.success($scope.safetyChecker);
1278                                 }
1279                                 $scope.pushStatus=data.policyData.split("&")[1];
1280                                 if($scope.pushStatus=="successPush"){
1281                                         Notification.success("Policy pushed successfully");
1282                                 }
1283                                 Notification.success("Policy Saved Successfully.");     
1284                         }else if ($scope.data == 'PolicyExists'){
1285                                                 $scope.savebutton = true;
1286                                                 Notification.error("Policy Already Exists with Same Name in Scope.");
1287                                         }
1288                 });
1289                 console.log($scope.data);
1290             },
1291             error : function(data){
1292                 Notification.error("Error Occured while saving Policy.");
1293             }
1294         });
1295     };
1296     
1297     $scope.validatePolicy = function(policy){
1298         document.getElementById("validate").innerHTML = "";
1299         var splitAt = '*';
1300         var dot ='.';
1301         var jsonPolicy = {};
1302         if(plainAttributeKeys != null){
1303                 for(a = 0; a < plainAttributeKeys.length; a++){
1304                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
1305                         console.log(splitPlainAttributeKey[1]); 
1306                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
1307                         var key = splitPlainAttributeKey[0];
1308                         if(searchElement == null || searchElement.nodeName == 'BUTTON'){
1309                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1310                                 key = splitPlainAttributeKey[0]+'@0';
1311                         }
1312                         if(searchElement != null){
1313                                 if (enumKeyList.indexOf(key) != -1){
1314                                                 if (splitPlainAttributeKey[1].indexOf("true") !== -1){
1315                                                         var multiSlect = [];
1316                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
1317                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
1318                                                                 }
1319                                                         jsonPolicy[key]= multiSlect;
1320                                                 }else{
1321                                                         jsonPolicy[key]= searchElement.value;
1322                                                 }
1323                                         if(searchElement.getAttribute("required")){
1324                                                 if(!searchElement.value){
1325                                                         return;
1326                                                 }
1327                                         } 
1328                                 } else {
1329                                         if(searchElement.value != null){
1330                                                 jsonPolicy[key]= searchElement.value;
1331                                                 if(searchElement.getAttribute("required")){
1332                                                         if(!searchElement.value){
1333                                                                 return;
1334                                                         }
1335                                                 }                                               
1336                                         }
1337                                 }
1338                         }
1339                 }
1340         }
1341         var uuu = "policyController/validate_policy.htm";        
1342         var postData={policyData: policy, policyJSON : jsonPolicy};
1343                 $.ajax({
1344                         type : 'POST',
1345                         url : uuu,
1346                         dataType: 'json',
1347                         contentType: 'application/json',
1348                         data: JSON.stringify(postData),
1349                         success : function(data){
1350                                 $scope.$apply(function(){
1351                                         $scope.validateData = data.data.replace(/\"/g, "");
1352                                         $scope.data=data.data.substring(1,8);
1353                                                 var size = data.data.length;
1354                                                 if($scope.data == 'success'){
1355                                                         Notification.success("Validation Success.");
1356                                                         $scope.savebutton = false;
1357                                                         if (size > 18){
1358                                                                 var displayWarning = data.data.substring(19,size  - 1);
1359                                                                 document.getElementById("validate").innerHTML = "Safe Policy Warning Message  :  "+displayWarning;
1360                                                                 document.getElementById("validate").style.color = "white";
1361                                                                 document.getElementById("validate").style.backgroundColor = "skyblue";
1362                                                         }
1363                                                 }else{
1364                                                         Notification.error("Validation Failed.");
1365                                                         document.getElementById("validate").innerHTML = $scope.validateData;
1366                                                         document.getElementById("validate").style.color = "white";
1367                                                         document.getElementById("validate").style.backgroundColor = "red";
1368                                                         $scope.savebutton = true;
1369                                                 }
1370                                                 
1371                                 });
1372                                 console.log($scope.data);       
1373                         },
1374                         error : function(data){
1375                                 Notification.error("Validation Failed.");
1376                                 $scope.savebutton = true;
1377                         }
1378                 });
1379     };
1380
1381     function extend(obj, src) {
1382         for (var key in src) {
1383             if (src.hasOwnProperty(key)) obj[key] = src[key];
1384         }
1385         return obj;
1386     }
1387 }]);/**
1388  * 
1389  */