2773df0939c3302a9c7096379d315e88f157fa80
[myslice.git] / plugins / sladialog / static / js / sladialog.js
1 /**
2  * MyPlugin:    demonstration plugin
3  * Version:     0.1
4  * Description: Template for writing new plugins and illustrating the different
5  *              possibilities of the plugin API.
6  *              This file is part of the Manifold project 
7  * Requires:    js/plugin.js
8  * URL:         http://www.myslice.info
9  * Author:      Jordan AugĂ© <jordan.auge@lip6.fr>
10  * Copyright:   Copyright 2012-2013 UPMC Sorbonne UniversitĂ©s
11  * License:     GPLv3
12  */
13
14 (function($){
15
16     var SlaDialog = Plugin.extend({
17
18         accepted_slas: {},
19         queries: [],
20
21         /** XXX to check
22          * @brief Plugin constructor
23          * @param options : an associative array of setting values
24          * @param element : 
25          * @return : a jQuery collection of objects on which the plugin is
26          *     applied, which allows to maintain chainability of calls
27          */
28         init: function(options, element) {
29             // for debugging tools
30             this.classname="SlaDialog";
31             // Call the parent constructor, see FAQ when forgotten
32             this._super(options, element);
33
34             /* Member variables */
35
36             /* Plugin events */
37
38             /* Setup query and record handlers */
39
40             // Explain this will allow query events to be handled
41             // What happens when we don't define some events ?
42             // Some can be less efficient
43             this.listen_query(options.query_uuid);
44             
45             /* GUI setup and event binding */
46             // call function
47             this.button_binding();
48
49             // Get testbeds with sla and store them in localStorage
50             //this.get_testbeds_with_sla();
51
52         },
53
54         get_testbeds_with_sla: function () {
55             return $.get('/sla/testbeds/', function(data) {
56                 if (typeof(Storage) !== "undefined") {
57                     if (!localStorage.getItem("sla_testbeds")) {
58                         var testbeds = data;
59                         localStorage.setItem("sla_testbeds", testbeds);
60                     }
61                 }
62             });
63         },
64
65         find_row: function(key)
66         {
67             // key in third position, column id = 2
68             var KEY_POS = 2;
69
70             var cols = $.grep(this.table.fnSettings().aoData, function(col) {
71                 return (col._aData[KEY_POS] == key);
72             } );
73
74             if (cols.length == 0)
75                 return null;
76             if (cols.length > 1)
77                 throw "Too many same-key rows in ResourceSelected plugin";
78
79             return cols[0];
80         },
81
82         check_template_status: function() {
83             for (var testbed in this.accepted_slas) {
84                 if (!this.accepted_slas[testbed]) { return false; }
85             }
86
87             return true;
88         },
89
90         /* PLUGIN EVENTS */
91         // on_show like in querytable
92
93
94         /* GUI EVENTS */
95
96         button_binding: function() {
97             var self = this;
98             $(".sla-accept-button").click(function() {
99                 // set SLA as accepted and remove warnings
100                 var id = $(this).closest(".row").attr("id");
101                 self.accepted_slas[id] = true;
102                 var is_ok = self.check_template_status();
103
104                 $(".sla-alert").show();
105                 $(this).button("complete");
106                 $(this).prop("disabled", true);
107
108                 if (is_ok) {
109                     // remove warnings
110                     // var warnings = manifold.query_store.get_record_state(resource_query.query_uuid, resource_key, STATE_WARNINGS);
111                 }
112             });
113
114             $(".sla-alert-close").click(function() {
115                 $(this).closest(".sla-alert").hide();
116             });
117         },
118
119         create_sla: function(record) {
120             var self = this;
121
122             var urns = [];
123
124             if (record.resource.length != 0 && typeof record.resource[0] === "object") {
125
126                 record.resource.forEach(function(r) {
127                     if ($.inArray(r.component_id, record.resource) == -1) { // if not already selected
128                         urns.push(r.component_id);
129                     }
130                 });
131
132                 var data = {
133                     "SLIVER_INFO_AGGREGATE_URN": record.resource[0].component_manager_id,
134                     "SLIVER_INFO_EXPIRATION": record.lease[0].end_time,     // FIXME: only working with leases
135                     "SLIVER_INFO_SLICE_URN": record.slice_urn,
136                     "SLIVER_INFO_CREATOR_URN": record.users[0],
137                     "SLIVER_INFO_URN": urns,
138                     "SLIVER_INFO_SLA_ID": self._getUUID()
139                 };
140
141                 console.log(data);
142
143                 $.post("/sla/agreements/create/", data)
144                     .done(function (response) {
145                         console.log("SLA created");
146                     });
147             }
148         },
149
150         uncheck: function(urn)
151         {
152 //            $('#slamodal').on('hidden.bs.modal', function(e){
153 //                $('#' + (urn).replace(/"/g,'')).click();
154 //                console.log('#' + (data.value).replace(/"/g,''));
155 //            });
156         },
157
158         // a function to bind events here: click change
159         // how to raise manifold events
160         set_state: function(data, username)
161         {
162             
163         },
164
165         post_agreement: function()
166         {
167             console.log(this.options.user);
168         },
169
170         /* GUI MANIPULATION */
171
172         // We advise you to write function to change behaviour of the GUI
173         // Will use naming helpers to access content _inside_ the plugin
174         // always refer to these functions in the remaining of the code
175
176         show_hide_button: function() 
177         {
178             // this.id, this.el, this.cl, this.elts
179             // same output as a jquery selector with some guarantees
180         },
181
182         /* TEMPLATES */
183
184         // see in the html template
185         // How to load a template, use of mustache
186
187         /* QUERY HANDLERS */
188
189         // How to make sure the plugin is not desynchronized
190         // He should manifest its interest in filters, fields or records
191         // functions triggered only if the proper listen is done
192
193         // no prefix
194
195         on_filter_added: function(filter)
196         {
197
198         },
199
200         on_field_state_changed: function(data)
201         {
202             var self = this;
203             // this.set_state(result, this.options.username);
204
205              switch(data.state) {
206                 case STATE_SET:
207                     switch(data.op) {
208                         case STATE_SET_IN_PENDING:
209                             if (typeof(data.value) == 'string') {
210                                 // data.value = urn
211                                 this._supports_sla(data.value)
212                                     .done( function(testbeds) {
213                                         var urn_regexp = /\+(.*?)\+/;
214                                         var urn = urn_regexp.exec(data.value)[1];
215                                         var pos = $.inArray(urn, testbeds);
216                                         if ( pos != -1) {
217                                             var id_ref = testbeds[pos].replace(/\.|:/g, "-");
218                                             $("#" + id_ref).data("urns").push(data.value);
219                                             $("#" + id_ref).show();
220                                             self.accepted_slas[id_ref] = false;
221                                             //$( "#sla_offers_list" ).append(
222                                             //    $("<li>").text("Testbed " + testbeds[pos] + " offers SLA for its resources")
223                                             //);
224                                         }
225                                     });
226                             }
227                             break;
228                         case STATE_SET_OUT:
229                             // data.value = urn
230                             if (typeof(data.value) == 'string') {
231                                 // data.value = urn
232                                 this._supports_sla(data.value)
233                                     .done( function(testbeds) {
234                                         var urn_regexp = /\+(.*?)\+/;
235                                         var urn = urn_regexp.exec(data.value)[1];
236                                         var pos = $.inArray(urn, testbeds);
237                                         if ( pos != -1) {
238                                             var id_ref = testbeds[pos].replace(/\.|:/g, "-");
239                                             var array = $("#" + id_ref).data("urns");
240                                             array.splice(array.indexOf(data.value), 1);
241
242                                             if ($("#" + id_ref).data("urns").length == 0) {
243                                                 $("#" + id_ref).hide();
244                                                 delete self.accepted_slas[id_ref];
245                                                 $(".sla-accept-button").button("reset");
246                                                 $(".sla-accept-button").prop("disabled", false);
247                                             }
248                                             //$( "#sla_offers_list" ).append(
249                                             //    $("<li>").text("Testbed " + testbeds[pos] + " offers SLA for its resources")
250                                             //);
251                                         }
252                                     });
253                             }
254                             break;
255                     }
256                     break;
257
258                 case STATE_WARNINGS:
259                     // Add resource to SLA
260                     // data.key = urn
261                     // data.value = {1: "SLA acceptance required..."}
262                     // this.change_status(data.key, data.value);
263                     break;
264              }
265         }, 
266
267         // ... be sure to list all events here
268
269         /* RECORD HANDLERS */
270         on_all_new_record: function(record)
271         {
272             //
273         },
274
275         on_new_record: function(record)
276         {
277             this.create_sla(record);
278         },
279
280         /* INTERNAL FUNCTIONS */
281         _dummy: function() {
282             // only convention, not strictly enforced at the moment
283         },
284
285         _supports_sla: function(resource_urn) {
286             return $.ajax("/sla/testbeds/");
287         },
288
289
290
291         _getUUID: function() {
292             return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
293                 var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
294                 return v.toString(16);
295             });
296         },
297
298     });
299
300     /* Plugin registration */
301     $.plugin('SlaDialog', SlaDialog);
302
303     // TODO Here use cases for instanciating plugins in different ways like in the pastie.
304
305 })(jQuery);