Resolved Policy GUI Issues
[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 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     $scope.refresh = function(){
29         if($scope.refreshCheck){
30                 $scope.policyNavigator.refresh();
31         }
32         $scope.modal('createNewPolicy', true);
33         $scope.temp.policy = "";
34     };
35     
36     $scope.modal = function(id, hide) {
37         return $('#' + id).modal(hide ? 'hide' : 'show');
38     };
39     
40     $('#ttlDate').datepicker({
41         dateFormat: 'dd/mm/yy',
42         changeMonth: true,
43         changeYear: true,
44         onSelect: function(date) {
45                 angular.element($('#ttlDate')).triggerHandler('input');
46         }
47     });
48     
49         if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly  != undefined){
50                 if ($scope.temp.policy.configName == undefined){
51                         $scope.isCheck = false;
52                 }else{
53                         $scope.isCheck = true;
54                 }
55         }else {
56                 $scope.isCheck = false;
57         }
58                 
59         PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
60                 var j = data;
61                 $scope.data = JSON.parse(j.data);
62                 console.log($scope.data);
63                 $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
64                 console.log($scope.onapNameDictionaryDatas);
65         }, function (error) {
66                 console.log("failed");
67         });
68
69         PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
70                 var j = data;
71                 $scope.data = JSON.parse(j.data);
72                 console.log($scope.data);
73                 $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
74                 console.log($scope.priorityDatas);
75         }, function (error) {
76                 console.log("failed");
77         });
78
79         PolicyAppService.getData('getDictionary/get_GroupPolicyScopeDataByName').then(function (data) {
80                 var j = data;
81                 $scope.data = JSON.parse(j.data);
82                 console.log($scope.data);
83                 $scope.groupPolicyScopeListDatas = JSON.parse($scope.data.groupPolicyScopeListDatas);
84                 console.log($scope.groupPolicyScopeListDatas);
85         }, function (error) {
86                 console.log("failed");
87         });
88
89         PolicyAppService.getData('getDictionary/get_MicroServiceConfigNameDataByName').then(function (data) {
90                 var j = data;
91                 $scope.data = JSON.parse(j.data);
92                 console.log($scope.data);
93                 $scope.microServiceCongigNameDictionaryDatas = JSON.parse($scope.data.microServiceCongigNameDictionaryDatas);
94                 console.log($scope.microServiceCongigNameDictionaryDatas);
95         }, function (error) {
96                 console.log("failed");
97         });
98
99         PolicyAppService.getData('getDictionary/get_MicroServiceLocationDataByName').then(function (data) {
100                 var j = data;
101                 $scope.data = JSON.parse(j.data);
102                 console.log($scope.data);
103                 $scope.microServiceLocationDictionaryDatas = JSON.parse($scope.data.microServiceLocationDictionaryDatas);
104                 console.log($scope.microServiceLocationDictionaryDatas);
105         }, function (error) {
106                 console.log("failed");
107         });
108
109         PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataByName').then(function (data) {
110                 var j = data;
111                 $scope.data = JSON.parse(j.data);
112                 console.log($scope.data);
113                 var inputModelList = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
114                 var unique = {};
115                 var uniqueList = [];
116                 for(var i = 0; i < inputModelList.length; i++){
117                         if(typeof unique[inputModelList[i]] == "undefined"){
118                                 unique[inputModelList[i]] = "";
119                                 uniqueList.push(inputModelList[i]);
120                         }
121                 }
122                 $scope.microServiceModelsDictionaryDatas = uniqueList;
123                 console.log($scope.microServiceModelsDictionaryDatas);
124         }, function (error) {
125                 console.log("failed");
126         });
127
128         PolicyAppService.getData('getDictionary/get_DCAEUUIDDataByName').then(function (data) {
129                 var j = data;
130                 $scope.data = JSON.parse(j.data);
131                 console.log($scope.data);
132                 $scope.dcaeUUIDDictionaryDatas = JSON.parse($scope.data.dcaeUUIDDictionaryDatas);
133                 console.log($scope.dcaeUUIDDictionaryDatas);
134         }, function (error) {
135                 console.log("failed");
136         });
137
138         PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
139                 var j = data;
140                 $scope.data = JSON.parse(j.data);
141                 console.log($scope.data);
142                 $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
143                 console.log($scope.riskTypeDictionaryDatas);
144         }, function (error) {
145                 console.log("failed");
146         });
147
148         PolicyAppService.getData('getDictionary/get_MicroServiceAttributeData').then(function (data) {
149                 var j = data;
150                 $scope.data = JSON.parse(j.data);
151                 console.log($scope.data);
152                 $scope.microServiceAttributeDictionaryDatas = JSON.parse($scope.data.microServiceAttributeDictionaryDatas);
153                 console.log($scope.microServiceAttributeDictionaryDatas);
154         }, function (error) {
155                 console.log("failed");
156         });
157             
158
159          $scope.choices = [];
160          $scope.attributeDatas = [{"attributes" : $scope.choices}];
161          
162          $scope.addNewChoice = function(value) {
163                  console.log(value);
164                  if(value != undefined){
165                         if (value.startsWith('div.')){
166                                 value = value.replace('div.','');
167                         }
168                         var parentElement = document.getElementById("div."+value);
169                         var div = document.getElementById(value+"@0");
170                         if(div != null){
171                                 var clone = div.cloneNode(true); 
172                                 var addElement = parentElement.childElementCount + 1;
173                                 clone.id = ''+value+'@'+addElement;
174                                 clone.value = '';
175                                 clone.className += ' child_single'; //here cloned is single element
176                                 document.getElementById("div."+value).appendChild(clone);
177                                 plainAttributeKeys.push(''+value+'@'+addElement);
178                         }else{
179                                 div = document.getElementById("div."+value+"@0");
180                                 
181                                 div.className += ' children_group'; //here is div with a group of children.
182                                 
183                                 var childElement = parentElement.firstElementChild;
184                                 var countParent = parentElement.childElementCount;
185                                 var childElementString = childElement.innerHTML;
186                                 var find = value+"@0";
187                                 var re = new RegExp(find, 'g');
188                                 childElementString = childElementString.replace(re,value+'@' + countParent);
189                                 var clone = childElement.cloneNode(true);
190                                 for (var ii = 0; ii < parentElement.childNodes.length; ii++){
191                             var childId = parentElement.childNodes[ii].id;
192                             if(ii = parentElement.childNodes.length){
193                                 var childnewId = childId.slice(0, -1);
194                                 var count = childId.slice(-1);
195                             }
196                         }
197                                 var countvalue = parseInt(count) + 1;
198                                 clone.id = childnewId+countvalue;
199                                 clone.value = '';
200                                 clone.innerHTML=childElementString;
201                                 document.getElementById("div."+value).appendChild(clone);
202                                 var selects = clone.getElementsByTagName("select");
203                                 var inputs = clone.getElementsByTagName("input");
204                                 var removeValues = [];
205                                 for(var i=0; i<inputs.length; i++){
206                                         if ($scope.temp.policy.ruleData!=undefined){
207                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
208                                                 if (checkValue!=undefined){
209                                                         if($scope.temp.policy.ruleData != null){
210                                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
211                                                                 document.getElementById(inputs[i].id).value = $scope.temp.policy.ruleData[inputs[i].id];
212                                                                 plainAttributeKeys.push(inputs[i].id);
213                                                         }
214                                                 } else {
215 //                                                      removeValues.push(inputs[i].id);
216                                                         plainAttributeKeys.push(inputs[i].id);
217                                                 }
218                                         }else {
219                                                 plainAttributeKeys.push(inputs[i].id);
220                                         }
221                                 }
222                                 
223                                 for(var i=0; i<selects.length; i++){
224                                         if ($scope.temp.policy.ruleData!=undefined){
225                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
226                                                 if (checkValue!=undefined){
227                                                         if($scope.temp.policy.ruleData != null){
228                                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
229                                                                 document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
230                                                                 plainAttributeKeys.push(selects[i].id);
231                                                         }
232                                                 } else {
233                                                         plainAttributeKeys.push(selects[i].id);
234                                                 }
235                                         }else {
236                                                 plainAttributeKeys.push(selects[i].id);
237                                         }
238                                 }
239                                 
240                                 for (var k=0; k<removeValues.length; k++){
241                                         var elem = document.getElementById(removeValues[k]);
242                                         elem.parentNode.removeChild(elem);
243                                 }
244                                 var ele = angular.element(document.getElementById("div."+value));
245                         $compile(ele.contents())($scope);
246                     $scope.$apply();
247                         }
248                  }
249          };
250          
251          $scope.removeChoice = function(value) {
252                  console.log(value);
253                  if(value != undefined){
254                          document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);     
255                  }
256          };
257          
258          $scope.pullVersion = function(serviceName) {
259                  console.log(serviceName);
260                  if(serviceName != undefined){
261                          var uuu = "policyController/getModelServiceVersioneData.htm";
262                          var postData={policyData: serviceName};
263                          $.ajax({
264                                  type : 'POST',
265                                  url : uuu,
266                                  dataType: 'json',
267                                  contentType: 'application/json',
268                                  data: JSON.stringify(postData),
269                                  success : function(data){
270                                          $scope.$apply(function(){
271                                                  $scope.microServiceModelsDictionaryVersionDatas = data[0].dcaeModelVersionData;
272                                          });
273                                  },
274                                  error : function(data){
275                                          alert("Error While Retriving the Template Layout Pattren.");
276                                  }
277                          });             
278                  }
279          };
280     
281     var splitDash = '-';
282         var splitEqual = '=';
283         var splitComma = ',';
284         var splitcolon = ':';
285         var splitsemicolon = ";";
286         var splitEnum = "],";
287         var plainAttributeKeys = [];
288         var matching = [];
289         var enumKeyList = [];
290         var dictionaryList = [];
291         var dictionaryNameList = [];
292     $scope.addDataToFields = function(serviceName, version){
293         if(serviceName != null && version !=null){
294                 var service=serviceName+"-v"+version;
295                 var myNode = document.getElementById("DynamicTemplate");
296                 myNode.innerHTML = '';
297             var uuu = "policyController/getDCAEMSTemplateData.htm";
298             var postData={policyData: service};
299             $.ajax({
300                 type : 'POST',
301                 url : uuu,
302                 dataType: 'json',
303                 contentType: 'application/json',
304                 data: JSON.stringify(postData),
305                 success : function(data){
306                     $scope.$apply(function(){
307                         $scope.addNewChoice();
308                         var plainAttributeKeys = [];
309                         $scope.dcaeModelData = data[0].dcaeModelData;
310                         $scope.dcaeJsonDate = data[0].jsonValue;
311                         console.log("$scope.dcaeJsonDate: " + $scope.dcaeJsonDate);     
312                         var attributes = $scope.dcaeModelData.attributes;
313                         var refAttributes = $scope.dcaeModelData.ref_attributes;
314                         var subAttributes =     $scope.dcaeModelData.sub_attributes;                            
315                         console.log("subAttributes: " + subAttributes); 
316                         
317                         var enumAttributes = $scope.dcaeModelData.enumValues;
318                         var annotation = $scope.dcaeModelData.annotation;
319                         var dictionary = $scope.microServiceAttributeDictionaryDatas;
320
321                         if (annotation == null || annotation.length<1){
322                                 $scope.isCheck = true;
323                         }else {
324                                 $scope.isCheck = false;
325                                 var annoationList = annotation.split(splitComma);
326                                 for (k = 0; k < annoationList.length; k++){
327                                         var splitAnnotation = annoationList[k].split(splitEqual);
328                                         if (splitAnnotation[1].includes("matching-true")){
329                                                 matching.push(splitAnnotation[0].trim());
330                                         }
331                                 }
332
333                         }
334
335                         if (dictionary!= null && dictionary.length>1){
336                                 for (m=0; m < dictionary.length; m += 1){
337                                         var keyCompare = dictionary[m].name;
338                                         var valueCompare = dictionary[m].value;
339                                         var valueModel = dictionary[m].modelName;
340                                         var conpairService = serviceName;
341                                         if (valueModel.includes('-v')){
342                                                 conpairService = service;
343                                         }
344                                         if(valueModel.localeCompare(conpairService) == 0){
345                                                 console.log(valueCompare);      
346                                                 dictionaryList.push(dictionary[m]);
347                                                 if (!dictionaryNameList.includes(dictionary[m].name)){
348                                                         dictionaryNameList.push(dictionary[m].name)
349                                                 }
350                                         }
351                                 }
352                         }
353
354                                 $scope.temp.policy.ruleGridData = [];
355                                 
356                                 $scope.jsonLayout($scope.dcaeJsonDate);
357                                 
358                     });
359                     if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
360                         var checkData = [];
361                         var data = [];
362                         if($scope.temp.policy.ruleData != null){
363                                 var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
364                                 propNames.forEach(function(name) {
365                                         data.push(name);
366                                 });
367                                 for(a = 0; a < data.length; a++){
368                                         var splitPlainAttributeKey1 = data[a].split(".");
369                                         if(splitPlainAttributeKey1[0].indexOf("@") != -1){
370                                                 var key = splitPlainAttributeKey1[0];
371                                                 checkData.push(key);
372                                         }
373                                 }
374                                 var unique = checkData.filter(onlyUnique);
375                                 for(i =0; i < unique.length; i++){
376                                         if(unique[i].indexOf("@0") == -1){
377                                                 var finalkey = unique[i].split("@")[0];
378                                                 $scope.addNewChoice(finalkey);
379                                         }       
380                                 }
381                         }
382                     }
383                     var ele = angular.element(document.getElementById("DynamicTemplate"));
384                         $compile(ele.contents())($scope);
385                     $scope.$apply();
386                 },
387                 error : function(data){
388                     alert("Error While Retriving the Template Layout Pattren.");
389                 }
390             });
391         }
392     };
393     
394     function getDictionary(attribute){
395         var dicName = attribute;
396         if(attribute){
397            if(attribute.includes(":")){
398                    dicName = attribute.split(":")[0];
399            }
400         }
401             var dictionaryRegExp = new RegExp(dicName);
402             listemunerateValues = [];
403             if (dictionaryRegExp.test(dictionaryNameList)) {
404                         for (p=0; p < dictionaryList.length; p += 1) {
405                                 if (dicName == dictionaryList[p].name) {
406                                         listemunerateValues.push(dictionaryList[p].value);
407                                 }
408                         }
409             }
410             return listemunerateValues;
411     }
412     
413     function getList(attribute) {
414                 var enumName = attribute;
415                 console.log("In getList: attribute => " + attribute);
416                 if(attribute){
417                    if(attribute.includes(":")){
418                            enumName = attribute.split(":")[0];
419                    }
420                 }   
421             var baseEnum = $scope.dcaeModelData.enumValues;
422             var enumList = [];
423             if(baseEnum != null){
424                 enumList = baseEnum.split(splitEnum);
425             }
426                 var enumAttributes;
427                 var patternTest = new RegExp(enumName);
428                 for (k=0; k < enumList.length; k += 1){
429                         if(patternTest.test(enumList[k]) == true){
430                                 enumAttributes = enumList[k].trim();
431                 }
432         }
433
434          if(enumAttributes){
435                 enumAttributes = enumAttributes.replace("[", "");
436                 enumAttributes = enumAttributes.replace("]", "");
437                 enumAttributes = enumAttributes.replace(/ /g, '');
438                         var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
439                         listemunerateValues  = dropListAfterCommaSplit[1].split(splitComma);
440                         //enumKeyList.push(attribute); 
441                 return listemunerateValues;
442          }
443          
444             return [];
445             }
446             
447             function getBooleanList(){
448                 var booleanList = [];
449                 booleanList.push(true);
450                 booleanList.push(false);
451                 return booleanList;
452             }
453             
454
455             function isArray(arrayTest) {
456                 return Object.prototype.toString.call(arrayTest) === '[object Array]';
457             }
458             var lableList = [];
459                 function deconstructJSON(dataTest, level , name) {
460                         var array = false;
461                         var label = level;
462                          var stringValue = "java.lang.String";
463                          var string = "string";
464                          var intValue = "int";
465                          var double = "double";
466                          var boolean = "boolean";
467                          var baseLevel = level;
468                          
469                         if (name.length > 1){
470                                 label = label + name + '.';
471                         }
472                         
473                     for (key in dataTest) {
474                         array = isArray(dataTest[key]);
475                         console.log(key , dataTest[key]);
476                 
477                         if (!!dataTest[key] && typeof(dataTest[key])=="object") {
478                                 if (array==false && key!=="0"){
479                                         $scope.labelLayout(label, key, array );                         
480                                 }
481                                 
482                                 if (array == true && key!=0){
483                                         lableList.push(key);
484                                 }
485                                 
486                                 if (lableList.length > 0){
487                                         array = true;
488                                 }
489                                 if ( key=="0"){
490                                         var newKey = lableList.pop();
491                                         $scope.labelLayout(baseLevel, newKey, array );
492                                         if (array){
493                                                 label = baseLevel + newKey + '@0.';
494                                         } else {
495                                                 label = baseLevel + newKey + '.';
496                                         }
497                                 }
498                                 deconstructJSON(dataTest[key] , label, key);
499                         } else {
500                                 var attirbuteLabel = label;
501                                 var defaultValue='';
502                                 var isRequired = false;
503                                 if (dataTest[key].includes('defaultValue-')){
504                                         defaultValue = dataTest[key].split('defaultValue-')[1];
505                                 }
506
507                                 if (key==="0"){
508                                         array = true;
509                                         attributekey = lableList.pop();
510                                         attirbuteLabel = baseLevel;
511                                 } else {
512                                         attributekey = key.split();
513                                 }
514                                 
515                                 if (dataTest[key].includes('required-true')){
516                                         isRequired = true;
517                                 }
518                                 
519                                 var subAttributes = $scope.dcaeModelData.sub_attributes;
520                                 
521                                 if(subAttributes){                                      
522                                         var jsonObject = JSON.parse(subAttributes);                                     
523                                         var allkeys = Object.keys(jsonObject);
524                                         if(allkeys){
525                                                 for (var k = 0; k < allkeys.length; k++) {
526                                                         var keyValue = allkeys[k];
527                                                         console.log(" keyValue:jsonObject["+keyValue+ "]: " + jsonObject[keyValue]);
528                                                         if(jsonObject[keyValue]){
529                                                                 var tempObject = jsonObject[keyValue];
530                                                                 if(tempObject && tempObject[key]){
531                                                                 if (tempObject[key].includes('required-true')){
532                                                                         isRequired = true;
533                                                                 }       
534                                                                 }
535                                                         }
536                                                 }                                               
537                                         }                                       
538                                 }
539                                 
540                                 switch (dataTest[key].split(splitcolon)[0]){
541                                         case stringValue:
542                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired);
543                                                 break;
544                                         case string:
545                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired);
546                                                 break;                                          
547                                         case intValue: 
548                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired);
549                                                 break;
550                                         case double:
551                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired);
552                                                 break;
553                                         case boolean:
554                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, array, dataTest[key], getBooleanList());
555                                                 break;
556                                         default:
557                                                 if (dataTest[key].includes('dictionary-')){
558                                                         var list = getDictionary(dataTest[key].split('dictionary-')[1]);
559                                                 }else{
560                                                         var list = getList(dataTest[key]);
561                                                 }
562                                                 if (list.length===0){
563                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired);
564                                                 }else{
565                                                         $scope.dropBoxLayout(attirbuteLabel, attributekey, array, dataTest[key], list);
566                                                 }
567                                                 break;
568                                 }
569                         }
570                     }
571                 }  
572
573             $scope.jsonLayout = function(dataTest){
574                 deconstructJSON(dataTest , "", "");
575             }
576             
577             
578             $scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired){
579                         $scope.temp.policy.ruleGridData.push(attibuteKey);                      
580                 var br = document.createElement("BR");
581                 
582                 var label = document.createElement("Label");
583                 var labeltext = null;
584                 var requiredLabName = "";
585                 if (matching.includes(attibuteKey)){
586                         labeltext = document.createTextNode(attibuteKey + "*!");                
587                 }else {
588                         //var labeltext = document.createTextNode(refattributeLabel);
589                         if(isRequired){
590                                 requiredLabName = attibuteKey + " *";
591                                 labeltext = document.createTextNode(requiredLabName);
592                         }else{
593                             labeltext = document.createTextNode(attibuteKey);   
594                         }
595                 }
596
597                 
598                 var divID = labelValue;
599                 
600                 if (labelValue.length  < 1){
601                         divID = "DynamicTemplate";
602                 }else if (labelValue.endsWith('.')){
603                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
604                 }
605                 
606                 label.appendChild(labeltext);
607                 
608                 var textField = document.createElement("INPUT");
609                 
610                 textField.setAttribute("class" , "form-control");
611                 textField.setAttribute("type" , "text");
612                 textField.setAttribute("style" , "width:300px;");
613                 textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
614                 var checkKey;
615                 if(attributeManyKey){
616                         checkKey = labelValue + attibuteKey+'@0';
617                         textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+'');
618                         var divTag = document.createElement("div");
619                         divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
620                         var addButton = document.createElement("BUTTON");
621                         var buttonaddLabel = document.createTextNode("+");       
622                         addButton.appendChild(buttonaddLabel); 
623                         addButton.setAttribute("id", labelValue + attibuteKey);
624                         addButton.setAttribute("class", "btn btn-add-remove");
625                         addButton.setAttribute("ng-click" ,  'addNewChoice("'+labelValue + attibuteKey+'");');
626                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
627                         var removeButton = document.createElement("BUTTON");
628                         var buttonremoveLabel = document.createTextNode("-");       
629                         removeButton.appendChild(buttonremoveLabel); 
630                         removeButton.setAttribute("class", "btn btn-add-remove");
631                         removeButton.setAttribute("ng-click" ,  'removeChoice("'+labelValue + attibuteKey+'");');
632                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
633                         document.getElementById(divID).appendChild(addButton); 
634                         document.getElementById(divID).appendChild(removeButton); 
635                         document.getElementById(divID).appendChild(label);  
636                         document.getElementById(divID).appendChild(textField); 
637                         document.getElementById(divID).appendChild(br); 
638                         document.getElementById(divID).appendChild(divTag); 
639                         
640                 }else{
641                         checkKey = labelValue + attibuteKey;
642                         textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
643                         if(requiredLabName.includes("*")){
644                                 textField.setAttribute("required", "true");
645                         }
646                         document.getElementById(divID).appendChild(label);  
647                         document.getElementById(divID).appendChild(textField);  
648                         document.getElementById(divID).appendChild(br); 
649
650                 }
651                 
652                 if(divID.includes("@0") && divID.includes("div.")){
653                         var firstChild_Id = divID.split("@0")[0];
654                         var firstChild_element = document.getElementById(firstChild_Id);
655                         if(firstChild_element){
656                                 firstChild_element.className += ' children_group';  //here is a div with a group of children.
657                         }
658                 }
659                 console.log('firstChild_Id: ' + firstChild_Id);
660                 console.log('divID: ' + divID);
661                 
662                 if (defaultValue.length > 0){   
663                         if(defaultValue.includes(":")){
664                                 defaultValue = defaultValue.split(":")[0];
665                                 if(defaultValue === "NA") {
666                                         defaultValue = "";
667                                 }                               
668                         }
669                         document.getElementById(checkKey).value = defaultValue;
670                 }
671                 
672                 if($scope.temp.policy.ruleData != null){
673                         //document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
674                         if (attributeManyKey){
675                                 var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
676                                 document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
677                                 var i =1 ;
678                                 while(true){
679                                         var newValue = $scope.temp.policy.ruleData[newCheckKey+'@'+i];
680                                         if(newValue==null){
681                                                 break;
682                                         }else{
683                                                 $scope.addNewChoice(newCheckKey);
684                                                 document.getElementById(newCheckKey+'@'+i).value = newValue;
685                                                 i = i+1;
686                                         }
687                                 }               
688                 
689                         }else{
690                                 document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
691                         }
692                 } 
693                 plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey); 
694     };
695   
696     $scope.labelLayout = function(labelValue, lableName, labelManyKey ){
697                 var label = document.createElement("Label")
698                 var divID = labelValue;
699                 if (labelValue.endsWith('.')){
700                         var workingLabel = labelValue.substring(0, labelValue.length-1);
701                 }else {
702                         var workingLabel = labelValue;
703                 }
704                 
705                 if (labelValue.length  < 1){
706                         divID = "DynamicTemplate";
707                 } else if (labelValue.endsWith('.')){
708                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
709                 }
710                 
711                 var labeltext = document.createTextNode(lableName);
712         
713                 label.appendChild(labeltext);
714                 
715                 var subAttributes = $scope.dcaeModelData.sub_attributes;
716
717                 if(labelManyKey){
718                         var addButton = document.createElement("BUTTON");
719                         var buttonLabel = document.createTextNode("+");       
720                         addButton.appendChild(buttonLabel); 
721                         addButton.setAttribute("class", "btn btn-add-remove");
722                         addButton.setAttribute("ng-click" ,  'addNewChoice("'+labelValue + lableName+'");');
723                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
724                         var removeButton = document.createElement("BUTTON");
725                         var buttonremoveLabel = document.createTextNode("-");       
726                         removeButton.appendChild(buttonremoveLabel); 
727                         removeButton.setAttribute("class", "btn btn-add-remove");
728                         removeButton.setAttribute("ng-click" ,  'removeChoice("'+labelValue +lableName+'");');
729                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly"); 
730                         document.getElementById(divID).appendChild(addButton); 
731                         document.getElementById(divID).appendChild(removeButton);
732                         document.getElementById(divID).appendChild(label);
733                         var id = "div."+labelValue+lableName;
734                         var divTag = document.createElement("div");
735                         divTag.setAttribute("id", id); 
736                         document.getElementById(divID).appendChild(divTag);
737                         
738                         var divTag = document.createElement("div");
739                         divTag.setAttribute("id", id +'@0');
740                         
741                         divTag.className += ' children_group'; //here is div with a group of children.
742                         
743                         document.getElementById(id).appendChild(divTag);
744                 }else{
745                         var divTag = document.createElement("div");
746                         divTag.setAttribute("id", "div."+labelValue+lableName);
747                         divTag.className += ' children_group'; //here is div with a group of children.
748                         document.getElementById(divID).appendChild(label);  
749                         document.getElementById(divID).appendChild(divTag);                     
750                 }
751     };
752
753     $scope.dropBoxLayout = function(labelLevel, attributeName, many , refValue, listemunerateValues){
754                 var br = document.createElement("BR");
755
756                 if (labelLevel.length  < 1){
757                         var divID = "DynamicTemplate";
758                 } else if (labelLevel.endsWith('.')){
759                         var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
760                 }       
761
762
763         var label = document.createElement("Label")
764         if (matching.includes(attributeName)){
765                 var labeltext = document.createTextNode(attributeName + "*!");
766         }else {
767                 var labeltext = document.createTextNode(attributeName);
768         }
769         label.appendChild(labeltext);
770
771         var listField = document.createElement("SELECT");
772         listField.setAttribute("class" , "form-control");
773         listField.setAttribute("style" , "width:300px;");
774         listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
775         
776         for (i=0; i < listemunerateValues.length; i += 1) {
777             option = document.createElement('option');
778             option.setAttribute('value', listemunerateValues[i]);
779             option.appendChild(document.createTextNode(listemunerateValues[i]));
780             listField.appendChild(option);
781         }
782         listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
783         
784         enumKeyList.push(attributeName);
785         
786         document.getElementById(divID).appendChild(label);  
787         document.getElementById(divID).appendChild(br); 
788                         
789         if(many == true){
790                 document.getElementById(divID).appendChild(listField).multiple = true;
791                 plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
792         }else {
793                 document.getElementById(divID).appendChild(listField).multiple = false;
794                 plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
795         }
796
797         if($scope.temp.policy.ruleData != null){
798                 if (many == true){
799                         document.getElementById(labelLevel +attributeName).options[0].selected = false;
800                         for (i=0; i < listemunerateValues.length; i += 1) {
801                                 var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
802                                 if (testValue === undefined){
803                                         testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
804                                         }
805                                 var location = listemunerateValues.indexOf(testValue);
806                                 if (location!=-1){
807                                         document.getElementById(labelLevel +attributeName).options[location].selected = true;
808                                         }
809                                 }                       
810                         }else {
811                         document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];    
812                                 
813                         }
814                 }
815     };
816     
817     function onlyUnique(value, index, self) { 
818         return self.indexOf(value) === index;
819     };
820     
821     
822     function checkDictionary(value){
823         for (i = 0; i < $scope.microServiceAttributeDictionaryDatas.length; i++) {
824                 if ($scope.microServiceAttributeDictionaryDatas[i].name.localeCompare(value)){
825                         return true;
826                 }
827         }
828         
829     }
830     $scope.savePolicy = function(policy){
831         if(policy.itemContent != undefined){
832                 $scope.refreshCheck = true; 
833                 $scope.policyNavigator = policy.itemContent;
834                 policy.itemContent = "";
835         }
836         $scope.savebutton = false;
837         var splitAt = '*';
838         var dot ='.';
839         var jsonPolicy = {};
840         if(plainAttributeKeys != null){
841                 for(a = 0; a < plainAttributeKeys.length; a++){
842                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
843                         console.log(splitPlainAttributeKey[1]); 
844                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
845                         var key = splitPlainAttributeKey[0];
846                 if(searchElement == null){
847                     searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
848                     key = splitPlainAttributeKey[0]+'@0';
849                 }else if (searchElement.nodeName == 'BUTTON'){
850                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
851                                 key = splitPlainAttributeKey[0]+'@0';
852                         }
853                         if(searchElement != null){
854                                 var keySplit = key.split(dot);
855                                 var elumentLocation = keySplit.length;
856                                 var enumKey = key;
857                                 if (elumentLocation > 1){
858                                         enumKey = keySplit[keySplit.length - 1];
859                                 }
860                                 if (enumKeyList.indexOf(enumKey) != -1){
861                                                 if (splitPlainAttributeKey[1].indexOf("true") !== -1){
862                                                         var multiSlect = [];
863                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
864                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
865                                                                 }
866                                                         jsonPolicy[key]= multiSlect;
867                                                 }else{
868                                                         console.log(" searchElement.value = > " + searchElement.value);
869                                                         jsonPolicy[key]= searchElement.value;
870                                                 }
871                                 } else {
872                                         if(searchElement.value != null){
873                                                         console.log(" searchElement.value = > " + searchElement.value);
874                                                 jsonPolicy[key]= searchElement.value;
875                                         }
876                                 }
877                         }
878                 }
879         }
880         var uuu = "policycreation/save_policy";
881         var postData={policyData: policy, policyJSON : jsonPolicy};
882         $.ajax({
883             type : 'POST',
884             url : uuu,
885             dataType: 'json',
886             contentType: 'application/json',
887             data: JSON.stringify(postData),
888             success : function(data){
889                 $scope.$apply(function(){
890                         $scope.data=data.policyData;
891                         if($scope.data == 'success'){
892                                 $scope.temp.policy.readOnly = 'true';
893                                 $scope.safetyChecker = data.policyData.split("#")[2];
894                                 if ($scope.safetyChecker!=undefined) {
895                                         Notification.success($scope.safetyChecker);
896                                 }
897                                 $scope.pushStatus=data.policyData.split("&")[1];
898                                 if($scope.pushStatus=="successPush"){
899                                         Notification.success("Policy pushed successfully");
900                                 }
901                                 Notification.success("Policy Saved Successfully.");     
902                         }else if ($scope.data == 'PolicyExists'){
903                                                 $scope.savebutton = true;
904                                                 Notification.error("Policy Already Exists with Same Name in Scope.");
905                                         }
906                 });
907                 console.log($scope.data);
908             },
909             error : function(data){
910                 Notification.error("Error Occured while saving Policy.");
911             }
912         });
913     };
914     
915     $scope.validatePolicy = function(policy){
916         document.getElementById("validate").innerHTML = "";
917         var splitAt = '*';
918         var dot ='.';
919         var jsonPolicy = {};
920         if(plainAttributeKeys != null){
921                 for(a = 0; a < plainAttributeKeys.length; a++){
922                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
923                         console.log(splitPlainAttributeKey[1]); 
924                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
925                         var key = splitPlainAttributeKey[0];
926                         if(searchElement == null){
927                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
928                                 key = splitPlainAttributeKey[0]+'@0';
929                         }else if (searchElement.nodeName == 'BUTTON'){
930                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
931                                 key = splitPlainAttributeKey[0]+'@0';
932                         }
933                         if(searchElement != null){
934                                 if (enumKeyList.indexOf(key) != -1){
935                                                 if (splitPlainAttributeKey[1].indexOf("true") !== -1){
936                                                         var multiSlect = [];
937                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
938                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
939                                                                 }
940                                                         jsonPolicy[key]= multiSlect;
941                                                 }else{
942                                                         jsonPolicy[key]= searchElement.value;
943                                                 }
944                                 } else {
945                                         if(searchElement.value != null){
946                                                 jsonPolicy[key]= searchElement.value;
947                                                 if(searchElement.getAttribute("required")){
948                                                         if(!searchElement.value){
949                                                                 return;
950                                                         }
951                                                 }                                               
952                                         }
953                                 }
954                         }
955                 }
956         }
957         var uuu = "policyController/validate_policy.htm";
958         var postData={policyData: policy, policyJSON : jsonPolicy};
959                 $.ajax({
960                         type : 'POST',
961                         url : uuu,
962                         dataType: 'json',
963                         contentType: 'application/json',
964                         data: JSON.stringify(postData),
965                         success : function(data){
966                                 $scope.$apply(function(){
967                                         $scope.validateData = data.data.replace(/\"/g, "");
968                                         $scope.data=data.data.substring(1,8);
969                                                 var size = data.data.length;
970                                                 if($scope.data == 'success'){
971                                                         Notification.success("Validation Success.");
972                                                         $scope.savebutton = false;
973                                                         if (size > 18){
974                                                                 var displayWarning = data.data.substring(19,size  - 1);
975                                                                 document.getElementById("validate").innerHTML = "Safe Policy Warning Message  :  "+displayWarning;
976                                                                 document.getElementById("validate").style.color = "white";
977                                                                 document.getElementById("validate").style.backgroundColor = "skyblue";
978                                                         }
979                                                 }else{
980                                                         Notification.error("Validation Failed.");
981                                                         document.getElementById("validate").innerHTML = $scope.validateData;
982                                                         document.getElementById("validate").style.color = "white";
983                                                         document.getElementById("validate").style.backgroundColor = "red";
984                                                         $scope.savebutton = true;
985                                                 }
986                                                 
987                                 });
988                                 console.log($scope.data);       
989                         },
990                         error : function(data){
991                                 Notification.error("Validation Failed.");
992                                 $scope.savebutton = true;
993                         }
994                 });
995     };
996
997     function extend(obj, src) {
998         for (var key in src) {
999             if (src.hasOwnProperty(key)) obj[key] = src[key];
1000         }
1001         return obj;
1002     }
1003 }]);