922220b102db64f5d04f25bb3048cf4f1c0e824d
[clamp.git] / src / main / resources / META-INF / resources / designer / scripts / OperationalPolicyCtrl.js
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License"); 
9  * you may not use this file except in compliance with the License. 
10  * You may obtain a copy of the License at
11  * 
12  * http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software 
15  * distributed under the License is distributed on an "AS IS" BASIS, 
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
17  * See the License for the specific language governing permissions and 
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  * 
22  */
23 app
24 .controller(
25 'operationalPolicyCtrl',
26 [
27     '$scope',
28     '$rootScope',
29     '$uibModalInstance',
30     'data',
31     'operationalPolicyService',
32     'dialogs',
33     function($scope, $rootScope, $uibModalInstance, data, operationalPolicyService, dialogs) {
34
35             console.log("//////operationalPolicyCtrl");
36             $scope.policy_ids = []
37             var allPolicies = {};
38             $scope.guardType = "GUARD_MIN_MAX";
39             $scope.number = 0;
40             $scope.clname="";
41             function getAllFormId() {
42
43                     return Array.from(document.getElementsByClassName("formId"));
44             }
45             function searchActiveFormId() {
46
47                     var formArray = getAllFormId();
48                     for (var i = 0, max = formArray.length; i < max; i++) {
49                             console.log("Search active FormId, current element " + formArray[i].id);
50                             if (formArray[i].style.display !== "none") {
51                                     console.log("Active form is:" + formArray[i].id);
52                                     return formArray[i];
53                             }
54                     }
55                     console.log("No active formId found !");
56             }
57
58             function add_one_more() {
59
60                     console.log("add one more");
61                     $("#nav_Tabs li").removeClass("active");
62                     // FormSpan contains a block of the form that is not being
63                     // displayed. We will create clones of that and add them to tabs
64                     var form = $("#formSpan").clone(true, true)
65                     var count = 0;
66                     // Each new tab will have the formId class attached to it. This way
67                     // we can track how many forms we currently have out there and
68                     // assign listeners to them
69                     if ($(".formId").length > 0) {
70                             var greatest = 0;
71                             var s = $(".formId");
72                             for (var i = 0; i < s.length; i++) {
73                                     if (parseInt($(s[i]).attr("id").substring(6)) > greatest) {
74                                             greatest = parseInt($(s[i]).attr("id").substring(6))
75                                     }
76                             }
77                             count = greatest + 1;
78                             $("#properties_tab").append(('<span class="formId" id="formId' + count + '"></span>'));
79                     } else {
80                             count++;
81                             $("#properties_tab").append('<span class="formId" id="formId1"></span>');
82                     }
83                     $("#add_one_more")
84                     .parent()
85                     .before(
86                     ' <li class="active"><a id="go_properties_tab'
87                     + count
88                     + '">new</a><button id="tab_close'
89                     + count
90                     + '" type="button" class="close tab-close-popup" aria-hidden="true" style="margin-top: -30px;margin-right: 5px">&times;</button></li>');
91                     $("#formId" + count).append(form.children());
92                     $(".formId").not($("#formId" + count)).css("display", "none");
93                     addCustListen(count);
94                     $("#formId" + count + " #id").val("new");
95                     return count;
96             }
97             function addCustListen(count) {
98
99                     $('#go_properties_tab' + count).click(function(event) {
100
101                             $("#nav_Tabs li").removeClass("active");
102                             $(this).parent().addClass("active");
103                             $("#formId" + count).css("display", "")
104                             $(".formId").not($("#formId" + count)).css("display", "none")
105                     })
106                     $('#tab_close' + count).click(function(event) {
107
108                             $(this).parent().remove();
109                             $scope.policy_ids.splice($scope.policy_ids.indexOf($("#formId" + count + " #id").val()), 1);
110                             $("#formId" + count).remove();
111                     })
112             }
113             function greatestIdNum() {
114
115                     var greatest = 0;
116                     var s = $(".formId");
117                     for (var i = 0; i < s.length; i++) {
118                             if (parseInt($(s[i]).attr("id").substring(6)) > greatest) {
119                                     greatest = parseInt($(s[i]).attr("id").substring(6))
120                             }
121                     }
122                     return greatest;
123             }
124             function serializeElement(element) {
125
126                     var o = {};
127                     var a = element.serializeArray();
128                     $.each(a, function() {
129
130                             if (o[this.name]) {
131                                     if (!o[this.name].push) {
132                                             o[this.name] = [ o[this.name] ];
133                                     }
134                                     o[this.name].push(this.value || '');
135                             } else {
136                                     o[this.name] = this.value || '';
137                             }
138                     });
139                     return o;
140             }
141             function savePolicyLocally() {
142
143                     var polForm = {}
144                     polForm = serializeElement($("#operationalPolicyHeaderForm"));
145                     var policiesArray = []
146                     allPolicies['guard_policies'] = [];
147                     $.each($(".formId"), function() {
148
149                             var policyProperties = serializeElement($("#" + this.id + " .policyProperties"));
150                             policyProperties["target"] = serializeElement($("#" + this.id + " .policyTarget"))
151                             policiesArray.push(policyProperties);
152                             // Now get the Guard
153                             if ($("#" + this.id + " #enableGuardPolicy").is(':checked')) {
154                                     allPolicies['guard_policies'].push(serializeElement($("#" + this.id + " .guardProperties")));
155                             }
156                     });
157                     polForm['policies'] = policiesArray;
158                     allPolicies['operational_policy'] = polForm;
159             }
160             function add_new_policy() {
161
162                     console.log("add new policy");
163                     // remove old gui forms
164                     for (var i = 1; i < ($(".formId").length + 1); i++) {
165                             $("#go_properties_tab" + i).parent().remove();
166                     }
167                     $(".formId").remove();
168                     $("#add_one_more").click();
169             }
170             function configureComponents(allPolicies) {
171
172                     console.log("load properties to op policy");
173                     // Set the header
174                     $.each($('#operationalPolicyHeaderForm').find('.form-control'), function() {
175
176                             $(this).val(allPolicies['operational_policy'][this.id]);
177                     });
178                     // Set the sub-policies
179                     $.each(allPolicies['operational_policy']['policies'], function(opPolicyElemIndex, opPolicyElemValue) {
180
181                             var formNum = add_one_more();
182                             $.each($('.policyProperties').find('.form-control'), function(opPolicyPropIndex, opPolicyPropValue) {
183
184                                     $("#formId"+formNum+" .policyProperties").find("#"+opPolicyPropValue.id).val(
185                                     allPolicies['operational_policy']['policies'][opPolicyElemIndex][opPolicyPropValue.id]);
186                             });
187                             // update the current tab label
188                             $("#go_properties_tab" + formNum).text(
189                             allPolicies['operational_policy']['policies'][opPolicyElemIndex]['id']);
190                             // Check if there is a guard set for it
191                             $.each(allPolicies['guard_policies'], function(guardElemIndex, guardElemValue) {
192
193                                     if (guardElemValue.recipe === $($("#formId" + formNum + " #recipe")[0]).val()) {
194                                             // Found one, set all guard prop
195                                             $.each($('.guardProperties').find('.form-control'), function(guardPropElemIndex,guardPropElemValue) {
196                                                 $("#formId"+formNum+" .guardProperties").find("#"+guardPropElemValue.id).val(
197                                                     allPolicies['guard_policies'][guardElemIndex][guardPropElemValue.id]);
198                                             });
199                                             // And finally enable the flag
200                                             $("#formId" + formNum + " #enableGuardPolicy").prop("checked", true);
201                                     }
202                             });
203                     });
204             }
205             
206             $scope.initTargetResourceId = function() {
207
208                         var recipe = $(event.target).val();
209
210                         var type = $(event.target).val();
211                         
212                         $('#resourceId').empty();
213                         $("#resourceId")
214                                         .append(
215                                                         $('<option></option>').val("")
216                                                                         .html(""));
217                         $("#resourceId").append(
218                                         $('<option></option>').val("Other:")
219                                                         .html("Other:"));
220                         
221                         var resourceVnf = getResourceDetailsProperty();
222                         if (type == "VNF"
223                                         && (null !== resourceVnf || undefined !== resourceVnf)) {
224                                 for ( var prop in resourceVnf) {
225                                         var name = resourceVnf[prop]["name"];
226                                         $("#resourceId").append(
227                                                         $('<option></option>')
228                                                                         .val(name).html(name));
229                                 }
230
231                         }
232                         var resourceVfc = getResourceDetailsVfcProperty();
233                         if (type == "VFC"
234                                         && (null !== resourceVfc || undefined !== resourceVfc)) {
235                                 if (recipe == 'VF Module Create'
236                                                 || recipe == 'VF Module Delete') {
237                                         for ( var prop in resourceVfc) {
238                                                 if (resourceVfc[prop]["isBase"] == false) {
239                                                         var name = resourceVfc[prop]["name"];
240                                                         $("#resourceId").append(
241                                                                         $('<option></option>')
242                                                                                         .val(name)
243                                                                                         .html(name));
244                                                 }
245                                         }
246                                 } 
247                         else 
248                         {
249                           for ( var prop in resourceVfc) {
250                                           var name = resourceVfc[prop]["name"];
251                                                         $("#resourceId").append(
252                                                                         $('<option></option>')
253                                                                                         .val(name).html(name));
254                                         }
255                                         } 
256                 }
257
258
259             $scope.changeGuardPolicyType = function() {
260
261                     var formItemActive = searchActiveFormId();
262                     if (formItemActive === undefined)
263                             return;
264                     if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_MIN_MAX") {
265                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").show();
266                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").hide();
267                     } else if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_YAML") {
268                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").hide();
269                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").show();
270                     }
271             }
272             $scope.initPolicySelect = function() {
273
274                     if (allPolicies['operational_policy'] === undefined || allPolicies['operational_policy'] === null) {
275                             allPolicies = getOperationalPolicyProperty();
276                     }
277                     // Provision all policies ID first
278                     if ($scope.policy_ids.length == 0 && allPolicies['operational_policy'] != undefined) {
279                             $.each(allPolicies['operational_policy']['policies'], function() {
280
281                                     $scope.policy_ids.push(this['id']);
282                             });
283                     }
284             }
285             $scope.init = function() {
286
287                     $(function() {
288                         $scope.clname=getLoopName();
289                             $("#add_one_more").click(function(event) {
290
291                                     console.log("add one more");
292                                     event.preventDefault();
293                                     $scope.policy_ids.push($("#formId" + add_one_more() + " #id").val());
294                             });
295                             if (allPolicies['operational_policy'] !== undefined && allPolicies['operational_policy'] !== null) {
296                                     // load properties
297                                     console.log("load properties");
298                                     configureComponents(allPolicies);
299                             } else {
300                                     console.log("create new policy");
301                                     add_new_policy();
302                             }
303                             $("#savePropsBtn").click(function(event) {
304
305                                     console.log("save properties triggered");
306                                     savePolicyLocally();
307                                     angular.element(document.getElementById('formSpan')).scope().submitForm(allPolicies);
308                                     $("#close_button").click();
309                             });
310                     });
311             }
312             $scope.init();
313             $scope.updateGuardRecipe = function(event) {
314
315                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
316                     // Get the second recipe (guard one) and update it
317                     $($("#formId" + formNum + " #recipe")[1]).val($(event.target).val());
318             }
319             // When we change the name of a policy
320             $scope.updateTabLabel = function(event) {
321
322                     // update policy id structure
323                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
324                     $scope.policy_ids.splice($scope.policy_ids.indexOf($("#formId" + formNum + " #id").val()), 1);
325                     $scope.policy_ids.push($(event.target).val());
326                     // Update the tab now
327                     $("#go_properties_tab" + formNum).text($(event.target).val());
328             }
329             $scope.close = function() {
330
331                     console.log("close");
332                     $uibModalInstance.close("closed");
333             };
334             $scope.submitForm = function(obj) {
335
336                     var operationalPolicies = getOperationalPolicies();
337                     if (obj !== null) {
338                             operationalPolicies[0]["configurationsJson"] = obj;
339                     }
340                     operationalPolicyService.saveOpPolicyProperties(operationalPolicies).then(function(pars) {
341
342                             updateOpPolicyProperties(operationalPolicies);
343                     }, function(data) {
344
345                     });
346             };
347     } ]);