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