Included Policy GUI Enhancements and validations
[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     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(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                                                 clone.className += ' child_single'; //here cloned is single element
188                                                 document.getElementById("div."+value).appendChild(clone);
189                                                 plainAttributeKeys.push(''+value+'@'+addElement);
190                                         }
191                                 }else{ //not view or edit
192                                         clone.className += ' child_single'; //here cloned is single element
193                                         document.getElementById("div."+value).appendChild(clone);
194                                         plainAttributeKeys.push(''+value+'@'+addElement);
195                                 }
196                         }else{
197                                 div = document.getElementById("div."+value+"@0");
198                                 
199                                 div.className += ' children_group'; //here is div with a group of children.
200                                 
201                                 var childElement = parentElement.firstElementChild;
202                                 var countParent = parentElement.childElementCount;
203                                 var childElementString = childElement.innerHTML;
204                                 var find = value+"@0";
205                                 var re = new RegExp(find, 'g');
206                                 childElementString = childElementString.replace(re,value+'@' + countParent);
207                                 var clone = childElement.cloneNode(true);
208                                 for (var ii = 0; ii < parentElement.childNodes.length; ii++){
209                             var childId = parentElement.childNodes[ii].id;
210                             if(ii = parentElement.childNodes.length){
211                                 var childnewId = childId.slice(0, -1);
212                                 var count = childId.slice(-1);
213                             }
214                         }
215                                 var countvalue = parseInt(count) + 1;
216                                 clone.id = childnewId+countvalue;
217                                 clone.value = '';
218                                 clone.innerHTML=childElementString;
219                                 document.getElementById("div."+value).appendChild(clone);
220                                 var selects = clone.getElementsByTagName("select");
221                                 var inputs = clone.getElementsByTagName("input");
222                                 var removeValues = [];
223                                 for(var i=0; i<inputs.length; i++){
224                                         if ($scope.temp.policy.ruleData!=undefined){
225                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
226                                                 if (checkValue!=undefined){
227                                                         if($scope.temp.policy.ruleData != null){
228                                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
229                                                                 document.getElementById(inputs[i].id).value = $scope.temp.policy.ruleData[inputs[i].id];
230                                                                 plainAttributeKeys.push(inputs[i].id);
231                                                         }
232                                                 } else {
233 //                                                      removeValues.push(inputs[i].id);
234                                                         plainAttributeKeys.push(inputs[i].id);
235                                                 }
236                                         }else {
237                                                 plainAttributeKeys.push(inputs[i].id);
238                                         }
239                                 }
240                                 
241                                 for(var i=0; i<selects.length; i++){
242                                         if ($scope.temp.policy.ruleData!=undefined){
243                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
244                                                 if (checkValue!=undefined){
245                                                         if($scope.temp.policy.ruleData != null){
246                                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
247                                                                 document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
248                                                                 plainAttributeKeys.push(selects[i].id);
249                                                         }
250                                                 } else {
251                                                         plainAttributeKeys.push(selects[i].id);
252                                                 }
253                                         }else {
254                                                 plainAttributeKeys.push(selects[i].id);
255                                         }
256                                 }
257                                 
258                                 for (var k=0; k<removeValues.length; k++){
259                                         var elem = document.getElementById(removeValues[k]);
260                                         elem.parentNode.removeChild(elem);
261                                 }
262                                 var ele = angular.element(document.getElementById("div."+value));
263                         $compile(ele.contents())($scope);
264                     $scope.$apply();
265                         }
266                  }
267          };
268          
269          $scope.removeChoice = function(value) {
270                  console.log(value);
271                  if(value != undefined){
272                          var c = document.getElementById("div."+value).childElementCount;
273                          
274                          if(c == 1){
275                                  Notification.error("The original one is not removable.");
276                                  return;
277                          }      
278                          document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);     
279                  }
280          };
281          
282          $scope.pullVersion = function(serviceName) {
283                  console.log(serviceName);
284                  if(serviceName != undefined){
285                          var uuu = "policyController/getModelServiceVersioneData.htm";
286                          var postData={policyData: serviceName};
287                          $.ajax({
288                                  type : 'POST',
289                                  url : uuu,
290                                  dataType: 'json',
291                                  contentType: 'application/json',
292                                  data: JSON.stringify(postData),
293                                  success : function(data){
294                                          $scope.$apply(function(){
295                                                  $scope.microServiceModelsDictionaryVersionDatas = data[0].dcaeModelVersionData;
296                                          });
297                                  },
298                                  error : function(data){
299                                          alert("Error While Retriving the Template Layout Pattren.");
300                                  }
301                          });             
302                  }
303          };
304     
305     var splitDash = '-';
306         var splitEqual = '=';
307         var splitComma = ',';
308         var splitcolon = ':';
309         var splitsemicolon = ";";
310         var splitEnum = "],";
311         var plainAttributeKeys = [];
312         var matching = [];
313         var enumKeyList = [];
314         var dictionaryList = [];
315         var dictionaryNameList = [];
316     $scope.addDataToFields = function(serviceName, version){
317         if(serviceName != null && version !=null){
318                 var service=serviceName+"-v"+version;
319                 var myNode = document.getElementById("DynamicTemplate");
320                 myNode.innerHTML = '';
321             var uuu = "policyController/getDCAEMSTemplateData.htm";
322             var postData={policyData: service};
323             $.ajax({
324                 type : 'POST',
325                 url : uuu,
326                 dataType: 'json',
327                 contentType: 'application/json',
328                 data: JSON.stringify(postData),
329                 success : function(data){
330                     $scope.$apply(function(){
331                         $scope.addNewChoice();
332                         var plainAttributeKeys = [];
333                         $scope.dcaeModelData = data[0].dcaeModelData;
334                         $scope.dcaeJsonDate = data[0].jsonValue;
335                         if(data[0].allManyTrueKeys){
336                                 console.log("$scope.allManyTrueKeys: " + $scope.allManyTrueKeys);
337                         }
338                         console.log("$scope.dcaeJsonDate: " + $scope.dcaeJsonDate);     
339                         var attributes = $scope.dcaeModelData.attributes;
340                         var refAttributes = $scope.dcaeModelData.ref_attributes;
341                         var subAttributes =     $scope.dcaeModelData.sub_attributes;                            
342                         console.log("subAttributes: " + subAttributes); 
343                         console.log("refAttributes: " + refAttributes); 
344                         var enumAttributes = $scope.dcaeModelData.enumValues;
345                         var annotation = $scope.dcaeModelData.annotation;
346                         var dictionary = $scope.microServiceAttributeDictionaryDatas;
347
348                         if (annotation == null || annotation.length<1){
349                                 $scope.isCheck = true;
350                         }else {
351                                 $scope.isCheck = false;
352                                 var annoationList = annotation.split(splitComma);
353                                 for (k = 0; k < annoationList.length; k++){
354                                         var splitAnnotation = annoationList[k].split(splitEqual);
355                                         if (splitAnnotation[1].includes("matching-true")){
356                                                 matching.push(splitAnnotation[0].trim());
357                                         }
358                                 }
359
360                         }
361
362                         if (dictionary!= null && dictionary.length>1){
363                                 for (m=0; m < dictionary.length; m += 1){
364                                         var keyCompare = dictionary[m].name;
365                                         var valueCompare = dictionary[m].value;
366                                         var valueModel = dictionary[m].modelName;
367                                         var conpairService = serviceName;
368                                         if (valueModel.includes('-v')){
369                                                 conpairService = service;
370                                         }
371                                         if(valueModel.localeCompare(conpairService) == 0){
372                                                 console.log(valueCompare);      
373                                                 dictionaryList.push(dictionary[m]);
374                                                 if (!dictionaryNameList.includes(dictionary[m].name)){
375                                                         dictionaryNameList.push(dictionary[m].name)
376                                                 }
377                                         }
378                                 }
379                         }
380
381                                 $scope.temp.policy.ruleGridData = [];
382                                 
383                                 $scope.jsonLayout($scope.dcaeJsonDate);
384                                 
385                     });
386                     
387                     if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){  // If it's veiw or edit
388                         
389                         if($scope.temp.policy.editPolicy){
390                                 $scope.isInitEditTemplate = true;
391                         }
392                         
393                         var checkData = [];
394                         var data = [];
395                             // If ruleData contains extra elements created by clicked add button 
396                                 if($scope.temp.policy.ruleData != null){
397                                         var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
398                                         propNames.forEach(function(name) {
399                                                 data.push(name);
400                                         });
401                                         
402                                         var extraElements = data;
403                                         
404                                         if(plainAttributeKeys != null){
405                                                 for(b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
406                                                         var newValue = plainAttributeKeys[b].split("*");
407                                                         for(a = 0; a < data.length; a++){
408                                                                 if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
409                                                                         extraElements.splice(a, 1);
410                                                                 }
411                                                         }
412                                         }
413                                         
414                                         //--- Populate these extra elements created by clicked add button 
415                                         for(a = 0; a < extraElements.length; a++){                              
416                                                 if(extraElements[a].includes("@")){
417                                                                 var n = extraElements[a].lastIndexOf("@");
418                                                                 if(n > 0){
419                                                                         var key = extraElements[a].substring(0, n+2); //include @x in key also by n+2 since x can be  1, or 2, or 3
420                                                                     checkData.push(key);
421                                                                 }
422                                                 }
423                                         }
424                                         var unique = checkData.filter(onlyUnique);
425                                         for(i =0; i < unique.length; i++){
426                                                 //remove @x and let addNewChoice add @1 or @2...
427                                                 var newKey = unique[i].substring(0, unique[i].length-2);
428                                                 console.log("newKey: " + newKey);       
429                                                 $scope.addNewChoice(newKey);
430                                         }
431                                 }
432                             }
433                         //After initially create the edit template, reset it to false.
434                             $scope.isInitEditTemplate = false;
435                     }
436                     var ele = angular.element(document.getElementById("DynamicTemplate"));
437                         $compile(ele.contents())($scope);
438                     $scope.$apply();
439                 },
440                 error : function(data){
441                     alert("Error While Retriving the Template Layout Pattren.");
442                 }
443             });
444         }
445     };
446     
447     function getDictionary(attribute){
448         var dicName = attribute;
449         if(attribute){
450            if(attribute.includes(":")){
451                    dicName = attribute.split(":")[0];
452            }
453         }
454             var dictionaryRegExp = new RegExp(dicName);
455             listemunerateValues = [];
456             if (dictionaryRegExp.test(dictionaryNameList)) {
457                         for (p=0; p < dictionaryList.length; p += 1) {
458                                 if (dicName == dictionaryList[p].name) {
459                                         listemunerateValues.push(dictionaryList[p].value);
460                                 }
461                         }
462             }
463             return listemunerateValues;
464     }
465     
466     function getList(attribute) {
467                 var enumName = attribute;
468                 console.log("In getList: attribute => " + attribute);
469                 if(attribute){
470                    if(attribute.includes(":")){
471                            enumName = attribute.split(":")[0];
472                    }
473                 }   
474             var baseEnum = $scope.dcaeModelData.enumValues;
475             var enumList = [];
476             if(baseEnum != null){
477                 enumList = baseEnum.split(splitEnum);
478             }
479                 var enumAttributes;
480                 var patternTest = new RegExp(enumName);
481                 for (k=0; k < enumList.length; k += 1){
482                         if(patternTest.test(enumList[k]) == true){
483                                 enumAttributes = enumList[k].trim();
484                 }
485         }
486
487          if(enumAttributes){
488                 enumAttributes = enumAttributes.replace("[", "");
489                 enumAttributes = enumAttributes.replace("]", "");
490                 enumAttributes = enumAttributes.replace(/ /g, '');
491                         var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
492                         listemunerateValues  = dropListAfterCommaSplit[1].split(splitComma);
493                         //enumKeyList.push(attribute); 
494                 return listemunerateValues;
495          }
496          
497             return [];
498             }
499             
500             function getBooleanList(){
501                 var booleanList = [];
502                 booleanList.push(true);
503                 booleanList.push(false);
504                 return booleanList;
505             }
506             
507
508             function isArray(arrayTest) {
509                 return Object.prototype.toString.call(arrayTest) === '[object Array]';
510             }
511             var lableList = [];
512                 function deconstructJSON(dataTest, level , name) {
513                         var array = false;
514                         var label = level;
515                          var stringValue = "java.lang.String";
516                          var string = "string";
517                          var intValue = "int";
518                          var integerValue = "integer";
519                          var double = "double";
520                          var boolean = "boolean";
521                          var baseLevel = level;
522                          
523                         if (name.length > 1){
524                                 label = label + name + '.';
525                         }
526                         
527                     for (key in dataTest) {
528                         array = isArray(dataTest[key]);
529                         console.log(key , dataTest[key]);
530                 
531                         if (!!dataTest[key] && typeof(dataTest[key])=="object") {
532                                 if (array==false && key!=="0"){
533                                         $scope.labelLayout(label, key, array );                         
534                                 }
535                                 
536                                 if (array == true && key!=0){
537                                         lableList.push(key);
538                                 }
539                                 
540                                 if (lableList.length > 0){
541                                         array = true;
542                                 }
543                                 if ( key==="0"){
544                                         var newKey = lableList.pop();
545                                         $scope.labelLayout(baseLevel, newKey, array );
546                                         if (array){
547                                                 label = baseLevel + newKey + '@0.';
548                                         } else {
549                                                 label = baseLevel + newKey + '.';
550                                         }
551                                 }
552                                 deconstructJSON(dataTest[key] , label, key);
553                         } else {
554                                 var attirbuteLabel = label;
555                                 var defaultValue='';
556                                 var isRequired = false;
557                                 if (dataTest[key].includes('defaultValue-')){
558                                         defaultValue = dataTest[key].split('defaultValue-')[1];
559                                 }
560
561                                 if (key==="0"){
562                                         array = true;
563                                         attributekey = lableList.pop();
564                                         attirbuteLabel = baseLevel;
565                                 } else {
566                                         attributekey = key.split();
567                                 }
568                                 
569                                 if (dataTest[key].includes('required-true')){
570                                         isRequired = true;
571                                 }
572                                 
573                                 var subAttributes = $scope.dcaeModelData.sub_attributes;
574                                 
575                                 if(subAttributes){                                      
576                                         var jsonObject = JSON.parse(subAttributes);                                     
577                                         var allkeys = Object.keys(jsonObject);
578                                         if(allkeys){
579                                                 for (var k = 0; k < allkeys.length; k++) {
580                                                         var keyValue = allkeys[k];
581                                                         console.log(" keyValue:jsonObject["+keyValue+ "]: " + jsonObject[keyValue]);
582                                                         if(jsonObject[keyValue]){
583                                                                 var tempObject = jsonObject[keyValue];
584                                                                 if(tempObject && tempObject[key]){
585                                                                 if (tempObject[key].includes('required-true')){
586                                                                         isRequired = true;
587                                                                 }       
588                                                                 }
589                                                         }
590                                                 }                                               
591                                         }                                       
592                                 }
593                                 
594                                 switch (dataTest[key].split(splitcolon)[0]){
595                                         case stringValue:
596                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
597                                                 break;
598                                         case string:
599                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
600                                                 break;                                          
601                                         case intValue: 
602                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
603                                                 break;
604                                         case integerValue: 
605                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
606                                                 break;                                          
607                                         case double:
608                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
609                                                 break;
610                                         case boolean:
611                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, array, dataTest[key], getBooleanList());
612                                                 break;
613                                         default:
614                                                 if (dataTest[key].includes('dictionary-')){
615                                                         var list = getDictionary(dataTest[key].split('dictionary-')[1]);
616                                                 }else{
617                                                         //--- get dropdown values from enumValues
618                                                         var list = getList(dataTest[key]);
619                                                 }
620                                                 if (list.length===0){ //not dropdown element
621                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
622                                                 }else{
623                                                         $scope.dropBoxLayout(attirbuteLabel, attributekey, array, dataTest[key], list, isRequired);
624                                                 }
625                                                 break;
626                                 }
627                         }
628                     }
629                 }  
630
631             $scope.jsonLayout = function(dataTest){
632                 deconstructJSON(dataTest , "", "");
633             }
634             
635             
636             $scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType ){
637                         $scope.temp.policy.ruleGridData.push(attibuteKey);                      
638                 var br = document.createElement("BR");
639                 
640                 var label = document.createElement("Label");
641                 var labeltext = null;
642                 var requiredLabName = "";
643                 if (matching.includes(attibuteKey)){
644                         labeltext = document.createTextNode(attibuteKey + "*!");        
645                         isRequired = true;  //set required as true for matching element
646                 }else {
647                         if(isRequired){
648                                 requiredLabName = attibuteKey + " *";
649                                 labeltext = document.createTextNode(requiredLabName);
650                         }else{
651                             labeltext = document.createTextNode(attibuteKey);   
652                         }
653                 }
654
655                 
656                 var divID = labelValue;
657                 
658                 if (labelValue.length  < 1){
659                         divID = "DynamicTemplate";
660                 }else if (labelValue.endsWith('.')){
661                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
662                 }
663                 
664                 label.appendChild(labeltext);
665                 
666                 var textField = document.createElement("INPUT");
667                 
668                 textField.setAttribute("class" , "form-control");
669                 if(dataType){
670                            if(dataType == "double"){
671                                    textField.setAttribute("type" , "number");
672                                    textField.setAttribute("step" , "any");
673                            }else{
674                               textField.setAttribute("type" , dataType);
675                            }
676                 }
677                 textField.setAttribute("style" , "width:300px;");
678                 textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
679                 var checkKey;
680                 if(attributeManyKey){
681                         checkKey = labelValue + attibuteKey+'@0';
682                         textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+''); 
683                         var divTag = document.createElement("div");
684                         divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
685                         var addButton = document.createElement("BUTTON");
686                         var buttonaddLabel = document.createTextNode("+");       
687                         addButton.appendChild(buttonaddLabel); 
688                         addButton.setAttribute("id", labelValue + attibuteKey);
689                         addButton.setAttribute("class", "btn btn-add-remove");
690                         addButton.setAttribute("ng-click" ,  'addNewChoice("'+labelValue + attibuteKey+'");');
691                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
692                         var removeButton = document.createElement("BUTTON");
693                         var buttonremoveLabel = document.createTextNode("-");       
694                         removeButton.appendChild(buttonremoveLabel); 
695                         removeButton.setAttribute("class", "btn btn-add-remove");
696                         removeButton.setAttribute("ng-click" ,  'removeChoice("'+labelValue + attibuteKey+'");');
697                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
698                         document.getElementById(divID).appendChild(addButton); 
699                         document.getElementById(divID).appendChild(removeButton); 
700                         document.getElementById(divID).appendChild(label); 
701                         var id = "div."+labelValue+attibuteKey;
702                         var divTag = document.createElement("div");
703                         divTag.setAttribute("id", id); 
704                         document.getElementById(divID).appendChild(divTag);
705                         textField.className += ' first_child';  
706                         if(isRequired){
707                                 textField.setAttribute("required", "true");
708                         }                       
709                         divTag.appendChild(textField);                  
710                         document.getElementById(divID).appendChild(divTag); 
711                         
712                 }else{
713                         checkKey = labelValue + attibuteKey;
714                         textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
715                         if(requiredLabName.includes("*")){
716                                 textField.setAttribute("required", "true");
717                         }
718                         document.getElementById(divID).appendChild(label);  
719                         document.getElementById(divID).appendChild(textField);  
720                         document.getElementById(divID).appendChild(br); 
721
722                 }
723                 
724                 if(divID.includes("@0") && divID.includes("div.")){
725                         var firstChild_Id = divID.split("@0")[0];
726                         var firstChild_element = document.getElementById(firstChild_Id);
727                         if(firstChild_element){
728                                 firstChild_element.className += ' children_group';  //here is a div with a group of children.
729                         }
730                 }
731                 console.log('firstChild_Id: ' + firstChild_Id);
732                 console.log('divID: ' + divID);
733                 
734                 if (defaultValue.length > 0){   
735                         if(defaultValue.includes(":")){
736                                 defaultValue = defaultValue.split(":")[0];
737                                 if(defaultValue === "NA") {
738                                         defaultValue = "";
739                                 }                               
740                         }
741                         document.getElementById(checkKey).value = defaultValue;
742                 }
743                 
744                 if($scope.temp.policy.ruleData != null){
745                         //document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
746                         if (attributeManyKey){
747                                 var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
748                                 document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
749                         }else{
750                                 document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
751                         }
752                 } 
753                 plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey); 
754     };
755   
756     $scope.labelLayout = function(labelValue, lableName, labelManyKey ){
757                 var label = document.createElement("Label")
758                 var divID = labelValue;
759                 if (labelValue.endsWith('.')){
760                         var workingLabel = labelValue.substring(0, labelValue.length-1);
761                 }else {
762                         var workingLabel = labelValue;
763                 }
764                 
765                 if (labelValue.length  < 1){
766                         divID = "DynamicTemplate";
767                 } else if (labelValue.endsWith('.')){
768                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
769                 }
770                 
771                 var labeltext = document.createTextNode(lableName);
772         
773                 label.appendChild(labeltext);
774                 
775                 var subAttributes = $scope.dcaeModelData.sub_attributes;
776
777                 if(labelManyKey){
778                         var addButton = document.createElement("BUTTON");
779                         var buttonLabel = document.createTextNode("+");       
780                         addButton.appendChild(buttonLabel); 
781                         addButton.setAttribute("class", "btn btn-add-remove");
782                         addButton.setAttribute("ng-click" ,  'addNewChoice("'+labelValue + lableName+'");');
783                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
784                         var removeButton = document.createElement("BUTTON");
785                         var buttonremoveLabel = document.createTextNode("-");       
786                         removeButton.appendChild(buttonremoveLabel); 
787                         removeButton.setAttribute("class", "btn btn-add-remove");
788                         removeButton.setAttribute("ng-click" ,  'removeChoice("'+labelValue +lableName+'");');
789                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly"); 
790                         document.getElementById(divID).appendChild(addButton); 
791                         document.getElementById(divID).appendChild(removeButton);
792                         document.getElementById(divID).appendChild(label);
793                         var id = "div."+labelValue+lableName;
794                         var divTag = document.createElement("div");
795                         divTag.setAttribute("id", id); 
796                         document.getElementById(divID).appendChild(divTag);
797                         
798                         var divTag = document.createElement("div");
799                         divTag.setAttribute("id", id +'@0');  
800                         
801                         divTag.className += ' children_group'; //here is div with a group of children.
802                         
803                         document.getElementById(id).appendChild(divTag);
804                 }else{
805                         var divTag = document.createElement("div");
806                         divTag.setAttribute("id", "div."+labelValue+lableName);
807                         divTag.className += ' children_group'; //here is div with a group of children.
808                         document.getElementById(divID).appendChild(label);  
809                         document.getElementById(divID).appendChild(divTag);                     
810                 }
811     };
812
813     $scope.dropBoxLayout = function(labelLevel, attributeName, many , refValue, listemunerateValues, isRequired){
814                 var br = document.createElement("BR");
815
816                 if (labelLevel.length  < 1){
817                         var divID = "DynamicTemplate";
818                 } else if (labelLevel.endsWith('.')){
819                         var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
820                 }       
821
822
823         var label = document.createElement("Label")
824         
825         var refAttributes = $scope.dcaeModelData.ref_attributes;
826         if(isRequired != true && refAttributes){ //check refAttributes also             
827                         var refAttributesList = refAttributes.split(splitComma);
828                         for (k = 0; k < refAttributesList.length; k++){
829                         var refAttribute = refAttributesList[k].split(splitEqual);                      
830                         if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
831                                 isRequired = true;
832                         }
833                         }
834         }
835         
836         if (matching.includes(attributeName)){
837                 var labeltext = document.createTextNode(attributeName + "*!");
838                 label.appendChild(labeltext);
839                 isRequired = true;  //set required as true for matching element
840         }else {
841                 var labeltext = document.createTextNode(attributeName);         
842                 if(isRequired){
843                         requiredLabName = attributeName+ " *";
844                         labeltext = document.createTextNode(requiredLabName);
845                 }else{
846                     labeltext = document.createTextNode(attributeName); 
847                 }
848         
849             label.appendChild(labeltext);               
850         }
851         label.appendChild(labeltext);
852
853         var listField = document.createElement("SELECT");
854         listField.setAttribute("class" , "form-control");
855         listField.setAttribute("style" , "width:300px;");
856         listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
857         
858         if(isRequired){
859            listField.setAttribute("required", true);
860         }
861         if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
862                 var optionFirst = document.createElement('option');
863                 optionFirst.setAttribute('value', "");
864                 listField.appendChild(optionFirst);     
865         }
866         
867         for (i=0; i < listemunerateValues.length; i += 1) {
868             option = document.createElement('option');
869             option.setAttribute('value', listemunerateValues[i]);
870             option.appendChild(document.createTextNode(listemunerateValues[i]));
871             option.setAttribute('value', listemunerateValues[i]);
872             listField.appendChild(option);
873         }
874         listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
875         
876         enumKeyList.push(attributeName);
877         
878         document.getElementById(divID).appendChild(label);  
879         document.getElementById(divID).appendChild(br); 
880                         
881         if(many == true){
882                 document.getElementById(divID).appendChild(listField).multiple = true;
883                 plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
884         }else {
885                 document.getElementById(divID).appendChild(listField).multiple = false;
886                 plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
887         }
888
889         if($scope.temp.policy.ruleData != null){
890                 if (many == true){
891                         document.getElementById(labelLevel +attributeName).options[0].selected = false;
892                         for (i=0; i < listemunerateValues.length; i += 1) {
893                                 var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
894                                 if (testValue === undefined){
895                                         testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
896                                         }
897                                 var location = listemunerateValues.indexOf(testValue);
898                                 if (location!=-1){
899                                         document.getElementById(labelLevel +attributeName).options[location].selected = true;
900                                         }
901                                 }                       
902                         }else {
903                         document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];    
904                                 
905                         }
906                 }
907     };
908     
909     function onlyUnique(value, index, self) { 
910         return self.indexOf(value) === index;
911     };
912     
913     
914     function checkDictionary(value){
915         for (i = 0; i < $scope.microServiceAttributeDictionaryDatas.length; i++) {
916                 if ($scope.microServiceAttributeDictionaryDatas[i].name.localeCompare(value)){
917                         return true;
918                 }
919         }
920         
921     }
922     $scope.savePolicy = function(policy){
923         if(policy.itemContent != undefined){
924                 $scope.refreshCheck = true; 
925                 $scope.policyNavigator = policy.itemContent;
926                 policy.itemContent = "";
927         }
928         $scope.savebutton = false;
929         var splitAt = '*';
930         var dot ='.';
931         var jsonPolicy = {};
932         if(plainAttributeKeys != null){
933                 for(a = 0; a < plainAttributeKeys.length; a++){
934                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
935                         console.log("splitPlainAttributeKey: " + splitPlainAttributeKey);       
936                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
937                         var key = splitPlainAttributeKey[0];
938                 if(searchElement == null){
939                     searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
940                     key = splitPlainAttributeKey[0]+'@0';
941                 }else if (searchElement.nodeName == 'BUTTON'){
942                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
943                                 key = splitPlainAttributeKey[0]+'@0';
944                         }
945                         if(searchElement != null){
946                                 var keySplit = key.split(dot);
947                                 var elumentLocation = keySplit.length;
948                                 var enumKey = key;
949                                 if (elumentLocation > 1){
950                                         enumKey = keySplit[keySplit.length - 1];
951                                 }
952                                 //check it is undefined or not
953                                 if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
954                                                 if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
955                                                         var multiSlect = [];
956                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
957                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
958                                                                 }
959                                                         jsonPolicy[key]= multiSlect;
960                                                 }else{
961                                                         console.log(" searchElement.value = > " + searchElement.value);
962                                                         jsonPolicy[key]= searchElement.value;
963                                                 }
964                                 } else {
965                                         if(searchElement.value != null){
966                                                         console.log(" searchElement.value = > " + searchElement.value);
967                                                 jsonPolicy[key]= searchElement.value;
968                                         }
969                                 }
970                         }
971                 }
972         }
973         var uuu = "policycreation/save_policy";
974         var postData={policyData: policy, policyJSON : jsonPolicy};
975         $.ajax({
976             type : 'POST',
977             url : uuu,
978             dataType: 'json',
979             contentType: 'application/json',
980             data: JSON.stringify(postData),
981             success : function(data){
982                 $scope.$apply(function(){
983                         $scope.data=data.policyData;
984                         if($scope.data == 'success'){
985                                 $scope.temp.policy.readOnly = 'true';
986                                 $scope.safetyChecker = data.policyData.split("#")[2];
987                                 if ($scope.safetyChecker!=undefined) {
988                                         Notification.success($scope.safetyChecker);
989                                 }
990                                 $scope.pushStatus=data.policyData.split("&")[1];
991                                 if($scope.pushStatus=="successPush"){
992                                         Notification.success("Policy pushed successfully");
993                                 }
994                                 Notification.success("Policy Saved Successfully.");     
995                         }else if ($scope.data == 'PolicyExists'){
996                                                 $scope.savebutton = true;
997                                                 Notification.error("Policy Already Exists with Same Name in Scope.");
998                                         }
999                 });
1000                 console.log($scope.data);
1001             },
1002             error : function(data){
1003                 Notification.error("Error Occured while saving Policy.");
1004             }
1005         });
1006     };
1007     
1008     $scope.validatePolicy = function(policy){
1009         document.getElementById("validate").innerHTML = "";
1010         var splitAt = '*';
1011         var dot ='.';
1012         var jsonPolicy = {};
1013         if(plainAttributeKeys != null){
1014                 for(a = 0; a < plainAttributeKeys.length; a++){
1015                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
1016                         console.log(splitPlainAttributeKey[1]); 
1017                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
1018                         var key = splitPlainAttributeKey[0];
1019                         if(searchElement == null){
1020                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1021                                 key = splitPlainAttributeKey[0]+'@0';
1022                         }else if (searchElement.nodeName == 'BUTTON'){
1023                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1024                                 key = splitPlainAttributeKey[0]+'@0';
1025                         }
1026                         if(searchElement != null){
1027                                 if (enumKeyList.indexOf(key) != -1){
1028                                                 if (splitPlainAttributeKey[1].indexOf("true") !== -1){
1029                                                         var multiSlect = [];
1030                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
1031                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
1032                                                                 }
1033                                                         jsonPolicy[key]= multiSlect;
1034                                                 }else{
1035                                                         jsonPolicy[key]= searchElement.value;
1036                                                 }
1037                                         if(searchElement.getAttribute("required")){
1038                                                 if(!searchElement.value){
1039                                                         return;
1040                                                 }
1041                                         } 
1042                                 } else {
1043                                         if(searchElement.value != null){
1044                                                 jsonPolicy[key]= searchElement.value;
1045                                                 if(searchElement.getAttribute("required")){
1046                                                         if(!searchElement.value){
1047                                                                 return;
1048                                                         }
1049                                                 }                                               
1050                                         }
1051                                 }
1052                         }
1053                 }
1054         }
1055         var uuu = "policyController/validate_policy.htm";
1056
1057         console.log("$scope.isCheck:" + $scope.isCheck);
1058         
1059         if($scope.isCheck == true){
1060                 if(("configName" in policy) == false){
1061                                 Notification.error("Validation Failed: configName is required");
1062                                 $scope.savebutton = true;
1063                                 return;
1064                 }
1065                 if(("location" in policy) == false){
1066                                 Notification.error("Validation Failed: location is required");
1067                                 $scope.savebutton = true;
1068                                 return;
1069                 }
1070                 if(("uuid" in policy) == false){
1071                                 Notification.error("Validation Failed: uuid is required");
1072                                 $scope.savebutton = true;
1073                                 return;
1074                 }
1075                 if(("policyScope" in policy) == false){
1076                                 Notification.error("Validation Failed: policyScope is required");
1077                                 $scope.savebutton = true;
1078                                 return;
1079                 }
1080         }        
1081         
1082         var postData={policyData: policy, policyJSON : jsonPolicy};
1083                 $.ajax({
1084                         type : 'POST',
1085                         url : uuu,
1086                         dataType: 'json',
1087                         contentType: 'application/json',
1088                         data: JSON.stringify(postData),
1089                         success : function(data){
1090                                 $scope.$apply(function(){
1091                                         $scope.validateData = data.data.replace(/\"/g, "");
1092                                         $scope.data=data.data.substring(1,8);
1093                                                 var size = data.data.length;
1094                                                 if($scope.data == 'success'){
1095                                                         Notification.success("Validation Success.");
1096                                                         $scope.savebutton = false;
1097                                                         if (size > 18){
1098                                                                 var displayWarning = data.data.substring(19,size  - 1);
1099                                                                 document.getElementById("validate").innerHTML = "Safe Policy Warning Message  :  "+displayWarning;
1100                                                                 document.getElementById("validate").style.color = "white";
1101                                                                 document.getElementById("validate").style.backgroundColor = "skyblue";
1102                                                         }
1103                                                 }else{
1104                                                         Notification.error("Validation Failed.");
1105                                                         document.getElementById("validate").innerHTML = $scope.validateData;
1106                                                         document.getElementById("validate").style.color = "white";
1107                                                         document.getElementById("validate").style.backgroundColor = "red";
1108                                                         $scope.savebutton = true;
1109                                                 }
1110                                                 
1111                                 });
1112                                 console.log($scope.data);       
1113                         },
1114                         error : function(data){
1115                                 Notification.error("Validation Failed.");
1116                                 $scope.savebutton = true;
1117                         }
1118                 });
1119     };
1120
1121     function extend(obj, src) {
1122         for (var key in src) {
1123             if (src.hasOwnProperty(key)) obj[key] = src[key];
1124         }
1125         return obj;
1126     }
1127 }]);