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