Draft operational policy rework
[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             function initTargetResourceId() {
58
59                     if (vf_Services !== null && vf_Services !== undefined) {
60                             // Set all the Resource Invariant UUID in the target resource ID
61                             // list (+Empty and other)
62                             Object.keys(vf_Services["shared"]["byVf"]).forEach(function(key) {
63
64                                     $("#targetResourceId").append($('<option></option>').val(key).html(key));
65                             });
66                     }
67             }
68             function add_one_more() {
69
70                     console.log("add one more");
71                     $("#nav_Tabs li").removeClass("active");
72                     // FormSpan contains a block of the form that is not being
73                     // displayed. We will create clones of that and add them to tabs
74                     var form = $("#formSpan").clone(true, true)
75                     var count = 0;
76                     // Each new tab will have the formId class attached to it. This way
77                     // we can track how many forms we currently have out there and
78                     // assign listeners to them
79                     if ($(".formId").length > 0) {
80                             var greatest = 0;
81                             var s = $(".formId");
82                             for (var i = 0; i < s.length; i++) {
83                                     if (parseInt($(s[i]).attr("id").substring(6)) > greatest) {
84                                             greatest = parseInt($(s[i]).attr("id").substring(6))
85                                     }
86                             }
87                             count = greatest + 1;
88                             $("#properties_tab").append(('<span class="formId" id="formId' + count + '"></span>'));
89                     } else {
90                             count++;
91                             $("#properties_tab").append('<span class="formId" id="formId1"></span>');
92                     }
93                     $("#add_one_more")
94                     .parent()
95                     .before(
96                     ' <li class="active"><a id="go_properties_tab'
97                     + count
98                     + '">new</a><button id="tab_close'
99                     + count
100                     + '" type="button" class="close tab-close-popup" aria-hidden="true" style="margin-top: -30px;margin-right: 5px">&times;</button></li>');
101                     $("#formId" + count).append(form.children());
102                     $(".formId").not($("#formId" + count)).css("display", "none");
103                     addCustListen(count);
104                     $("#formId" + count + " #id").val("new");
105                     return count;
106             }
107             function addCustListen(count) {
108
109                     $('#go_properties_tab' + count).click(function(event) {
110
111                             $("#nav_Tabs li").removeClass("active");
112                             $(this).parent().addClass("active");
113                             $("#formId" + count).css("display", "")
114                             $(".formId").not($("#formId" + count)).css("display", "none")
115                     })
116                     $('#tab_close' + count).click(function(event) {
117
118                             $(this).parent().remove();
119                             $scope.policy_ids.splice($scope.policy_ids.indexOf($("#formId" + count + " #id").val()), 1);
120                             $("#formId" + count).remove();
121                     })
122             }
123             function greatestIdNum() {
124
125                     var greatest = 0;
126                     var s = $(".formId");
127                     for (var i = 0; i < s.length; i++) {
128                             if (parseInt($(s[i]).attr("id").substring(6)) > greatest) {
129                                     greatest = parseInt($(s[i]).attr("id").substring(6))
130                             }
131                     }
132                     return greatest;
133             }
134             function serializeElement(element) {
135
136                     var o = {};
137                     var a = element.serializeArray();
138                     $.each(a, function() {
139
140                             if (o[this.name]) {
141                                     if (!o[this.name].push) {
142                                             o[this.name] = [ o[this.name] ];
143                                     }
144                                     o[this.name].push(this.value || '');
145                             } else {
146                                     o[this.name] = this.value || '';
147                             }
148                     });
149                     return o;
150             }
151             function savePolicyLocally() {
152
153                     var polForm = {}
154                     polForm = serializeElement($("#operationalPolicyHeaderForm"));
155                     var policiesArray = []
156                     allPolicies['guard_policies'] = [];
157                     $.each($(".formId"), function() {
158
159                             var policyProperties = serializeElement($("#" + this.id + " .policyProperties"));
160                             policyProperties["target"] = serializeElement($("#" + this.id + " .policyTarget"))
161                             policiesArray.push(policyProperties);
162                             // Now get the Guard
163                             if ($("#" + this.id + " #enableGuardPolicy").is(':checked')) {
164                                     allPolicies['guard_policies'].push(serializeElement($("#" + this.id + " .guardProperties")));
165                             }
166                     });
167                     polForm['policies'] = policiesArray;
168                     allPolicies['operational_policy'] = polForm;
169             }
170             function add_new_policy() {
171
172                     console.log("add new policy");
173                     // remove old gui forms
174                     for (var i = 1; i < ($(".formId").length + 1); i++) {
175                             $("#go_properties_tab" + i).parent().remove();
176                     }
177                     $(".formId").remove();
178                     $("#add_one_more").click();
179             }
180             function configureComponents(allPolicies) {
181
182                     console.log("load properties to op policy");
183                     // Set the header
184                     $.each($('#operationalPolicyHeaderForm').find('.form-control'), function() {
185
186                             $(this).val(allPolicies['operational_policy'][this.id]);
187                     });
188                     // Set the sub-policies
189                     $.each(allPolicies['operational_policy']['policies'], function(opPolicyElemIndex, opPolicyElemValue) {
190
191                             var formNum = add_one_more();
192                             $.each($('.policyProperties').find('.form-control'), function(opPolicyPropIndex, opPolicyPropValue) {
193
194                                     $("#formId"+formNum+" .policyProperties").find("#"+opPolicyPropValue.id).val(
195                                     allPolicies['operational_policy']['policies'][opPolicyElemIndex][opPolicyPropValue.id]);
196                             });
197                             // update the current tab label
198                             $("#go_properties_tab" + formNum).text(
199                             allPolicies['operational_policy']['policies'][opPolicyElemIndex]['id']);
200                             // Check if there is a guard set for it
201                             $.each(allPolicies['guard_policies'], function(guardElemIndex, guardElemValue) {
202
203                                     if (guardElemValue.recipe === $($("#formId" + formNum + " #recipe")[0]).val()) {
204                                             // Found one, set all guard prop
205                                             $.each($('.guardProperties').find('.form-control'), function(guardPropElemIndex,guardPropElemValue) {
206                                                 $("#formId"+formNum+" .guardProperties").find("#"+guardPropElemValue.id).val(
207                                                     allPolicies['guard_policies'][guardElemIndex][guardPropElemValue.id]);
208                                             });
209                                             // And finally enable the flag
210                                             $("#formId" + formNum + " #enableGuardPolicy").prop("checked", true);
211                                     }
212                             });
213                     });
214             }
215
216             $scope.changeGuardPolicyType = function() {
217
218                     var formItemActive = searchActiveFormId();
219                     if (formItemActive === undefined)
220                             return;
221                     if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_MIN_MAX") {
222                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").show();
223                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").hide();
224                     } else if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_YAML") {
225                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").hide();
226                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").show();
227                     }
228             }
229             $scope.initPolicySelect = function() {
230
231                     if (allPolicies['operational_policy'] === undefined || allPolicies['operational_policy'] === null) {
232                             allPolicies = getOperationalPolicyProperty();
233                     }
234                     // Provision all policies ID first
235                     if ($scope.policy_ids.length == 0 && allPolicies['operational_policy'] != undefined) {
236                             $.each(allPolicies['operational_policy']['policies'], function() {
237
238                                     $scope.policy_ids.push(this['id']);
239                             });
240                     }
241             }
242             $scope.init = function() {
243
244                     $(function() {
245                         $scope.clname=getLoopName();
246                             $("#add_one_more").click(function(event) {
247
248                                     console.log("add one more");
249                                     event.preventDefault();
250                                     $scope.policy_ids.push($("#formId" + add_one_more() + " #id").val());
251                             });
252                             if (allPolicies['operational_policy'] !== undefined && allPolicies['operational_policy'] !== null) {
253                                     // load properties
254                                     console.log("load properties");
255                                     configureComponents(allPolicies);
256                             } else {
257                                     console.log("create new policy");
258                                     add_new_policy();
259                             }
260                             $("#savePropsBtn").click(function(event) {
261
262                                     console.log("save properties triggered");
263                                     savePolicyLocally();
264                                     angular.element(document.getElementById('formSpan')).scope().submitForm(allPolicies);
265                                     $("#close_button").click();
266                             });
267                             initTargetResourceId();
268                     });
269             }
270             $scope.init();
271             $scope.updateGuardRecipe = function(event) {
272
273                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
274                     // Get the second recipe (guard one) and update it
275                     $($("#formId" + formNum + " #recipe")[1]).val($(event.target).val());
276             }
277             // When we change the name of a policy
278             $scope.updateTabLabel = function(event) {
279
280                     // update policy id structure
281                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
282                     $scope.policy_ids.splice($scope.policy_ids.indexOf($("#formId" + formNum + " #id").val()), 1);
283                     $scope.policy_ids.push($(event.target).val());
284                     // Update the tab now
285                     $("#go_properties_tab" + formNum).text($(event.target).val());
286             }
287             $scope.close = function() {
288
289                     console.log("close");
290                     $uibModalInstance.close("closed");
291             };
292             $scope.submitForm = function(obj) {
293
294                     var operationalPolicies = getOperationalPolicies();
295                     if (obj !== null) {
296                             operationalPolicies[0]["configurationsJson"] = obj;
297                     }
298                     operationalPolicyService.saveOpPolicyProperties(operationalPolicies).then(function(pars) {
299
300                             updateOpPolicyProperties(operationalPolicies);
301                     }, function(data) {
302
303                     });
304             };
305     } ]);