Merge branch 'onelab' of ssh://git.onelab.eu/git/myslice into onelab
[unfold.git] / plugins / queryupdater / static / js / queryupdater.js
1 /**
2  * MySlice QueryUpdater plugin
3  * Version: 0.1.0
4  * URL: http://www.myslice.info
5  * Description: display of selected resources
6  * Requires: 
7  * Author: The MySlice Team
8  * Copyright: Copyright 2012 UPMC Sorbonne Universités
9  * License: GPLv3
10  */
11
12 (function( $ ){
13
14     var debug=false;
15     debug=true;
16
17     // XXX record selected (multiple selection ?)
18     // XXX record disabled ?
19     // XXX out of sync plugin ?
20     // XXX out of date record ?
21     // record tags ???
22     //
23     // criticality of the absence of a handler in a plugin
24     // non-critical only can have switch case
25     // 
26     // Record state through the query cycle
27
28
29     var QueryUpdater = Plugin.extend({
30
31         init: function(options, element) {
32                 this.classname="queryupdater";
33             this._super(options, element);
34
35             var self = this;
36
37             this.initial = Array();
38
39             this.table = this.elmt('table').dataTable({
40 // the original querytable layout was
41 //                sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
42 // however the bottom line with 'showing blabla...' and the navigation widget are not really helpful
43                 sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t>",
44 // so this does not matter anymore now that the pagination area is turned off
45 //                sPaginationType: 'bootstrap',
46                 bAutoWidth: true,
47 //                bJQueryUI      : true,
48 //                bRetrieve      : true,
49 //                sScrollX       : '100%',                 // Horizontal scrolling 
50 //                bSortClasses   : false,              // Disable style for the sorted column
51 //                aaSorting      : [[ 0, 'asc' ]],        // Default sorting on URN
52 //                fnDrawCallback: function() {      // Reassociate close click every time the table is redrawn
53 //                    /* Prevent to loop on click while redrawing table  */
54 //                    $('.ResourceSelectedClose').unbind('click');
55 //                    /* Handle clicks on close span */
56 //                    /* Reassociate close click every time the table is redrawn */
57 //                    $('.ResourceSelectedClose').bind('click', self, self._close_click);
58 //                }
59              });
60             
61             // XXX This should not be done at init...
62             this.elmt('update').click(this, this.do_update);
63             this.elmt('refresh').click(this, this.do_refresh);
64             this.elmt('reset').click(this, this.do_reset);
65             this.elmt('clear_annotations').click(this, this.do_clear_annotations);
66
67             this.listen_query(options.query_uuid);
68         },
69
70         /*************************** PLUGIN EVENTS ****************************/
71
72         /***************************** GUI EVENTS *****************************/
73
74         do_update: function(e) {
75             var self = e.data;
76
77             var username = e.data.options.username;
78             var urn = data.value;
79             // XXX check that the query is not disabled
80
81             console.log("DATA VALUE: " + data.value);
82
83             if (data.value.toLowerCase().indexOf("iminds") >= 0){
84
85                 $('#sla_dialog').show();
86                 $('#slamodal').modal('show');
87                 
88                 $(document).ready(function() {
89                     $("#accept_sla").click(function(){
90                         console.log("SLA ACCEPTED");
91                         console.log("With username: " + username);
92                         if(urn.toLowerCase().indexOf("wall2") >= 0){ 
93                             $.post("/sla/agreements/simplecreate", 
94                                 { "template_id": "iMindsServiceVirtualwall",
95                                   "user": username,
96                                   "expiration_time": new Date() // jgarcia: FIXME
97                                 });
98                         } else if(urn.toLowerCase().indexOf("wilab2") >= 0){
99                             $.post("/sla/agreements/simplecreate", 
100                                 { "template_id":"iMindsServiceWiLab2",
101                                   "user":username,
102                                   "expiration_time": new Date() // jgarcia: FIXME
103                                 });
104                         }
105                         $('#slamodal').modal('hide');
106                         self.spin();
107                         console.log("Executing do_update after sending SLA");
108                         // XXX check that the query is not disabled
109                         manifold.raise_event(self.options.query_uuid, RUN_UPDATE);
110
111                         // how to stop the spinning after the event? 
112                         // this should be triggered by some on_updatequery_done ?
113                     }); 
114                 });
115
116                 $(document).ready(function() {
117                     $("#dismiss_sla").click(function(){
118                         console.log("SLA NOT ACCEPTED");
119                         $('#slamodal').modal('hide');
120                     }); 
121                 });
122
123             } else {
124                 self.spin();
125                 console.log("do_update");
126                 // XXX check that the query is not disabled
127                 manifold.raise_event(self.options.query_uuid, RUN_UPDATE);
128
129                 // how to stop the spinning after the event? 
130                 // this should be triggered by some on_updatequery_done ?
131             }
132
133         },
134
135         // related buttons are also disabled in the html template
136         do_refresh: function(e)
137         {
138             throw 'resource_selected.do_refresh Not implemented';
139         },
140
141         do_reset: function(e)
142         {
143             throw 'queryupdater.do_reset Not implemented';
144         },
145
146         do_clear_annotations: function(e)
147         {
148             throw 'queryupdater.do_clear_annotations Not implemented';
149         },
150         
151         /************************** GUI MANIPULATION **************************/
152
153         
154         set_button_state: function(name, state)
155         {
156             this.elmt(name).attr('disabled', state ? false : 'disabled');
157         },
158
159         clear: function()
160         {
161
162         },
163
164         find_row: function(key)
165         {
166             // key in third position, column id = 2
167             var KEY_POS = 2;
168
169             var cols = $.grep(this.table.fnSettings().aoData, function(col) {
170                 return (col._aData[KEY_POS] == key);
171             } );
172
173             if (cols.length == 0)
174                 return null;
175             if (cols.length > 1)
176                 throw "Too many same-key rows in ResourceSelected plugin";
177
178             return cols[0];
179         },
180
181         set_state: function(data)
182         {
183             console.log("function set_state");
184             var action;
185             var msg;
186             var button = '';
187
188             var row;
189             
190             // make sure the change is visible : toggle on the whole plugin
191             // this might have to be made an 'auto-toggle' option of this plugin..
192             // also it might be needed to be a little finer-grained here
193
194         // XXX we don't want to show automaticaly the pending when a checkbox is checked
195             //this.toggle_on();
196             
197             switch(data.request) {
198                 case FIELD_REQUEST_ADD_RESET:
199                 case FIELD_REQUEST_REMOVE_RESET:
200                     // find line and delete it
201                     row = this.find_row(data.value);
202                     if (row)
203                         this.table.fnDeleteRow(row.nTr);
204                         $("#badge-pending").data('number', $("#badge-pending").data('number') - 1 );
205                         $("#badge-pending").text($("#badge-pending").data('number'));
206                     return;
207                 case FIELD_REQUEST_CHANGE:
208                     action = 'UPDATE';
209                     break;
210                 case FIELD_REQUEST_ADD:
211                     action = 'ADD';
212                     break;
213                 case FIELD_REQUEST_REMOVE:
214                     action = 'REMOVE';
215                     break;
216             }
217
218             switch(data.status) {
219                 case FIELD_REQUEST_PENDING:
220                     msg   = 'PENDING';
221                     button = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='" + data.key + "'/>";
222                     break;
223                 case FIELD_REQUEST_SUCCESS:
224                     msg   = 'SUCCESS';
225                     break;
226                 case FIELD_REQUEST_FAILURE:
227                     msg   = 'FAILURE';
228                     break;
229             }
230
231             var status = msg + status;
232
233             
234
235             // find line
236             // if no, create it, else replace it
237             // XXX it's not just about adding lines, but sometimes removing some
238             // XXX how do we handle status reset ?
239             data.value = JSON.stringify(data.value);
240             row = this.find_row(data.value);
241             newline = [
242                 action,
243                 data.key,
244                 data.value,
245                 msg,
246                 button
247             ];
248             if (!row) {
249                 // XXX second parameter refresh = false can improve performance. todo in querytable also
250                 this.table.fnAddData(newline);
251                 row = this.find_row(data.value);
252                 $("#badge-pending").data('number', $("#badge-pending").data('number') + 1 );
253                 $("#badge-pending").text($("#badge-pending").data('number'));
254             } else {
255                 // Update row text...
256                 this.table.fnUpdate(newline, row.nTr);
257             }
258
259             // Change cell color according to status
260             if (row) {
261                 $(row.nTr).removeClass('add remove')
262                 var cls = action.toLowerCase();
263                 if (cls)
264                     $(row.nTr).addClass(cls);
265             }
266         },
267
268         /*************************** QUERY HANDLER ****************************/
269
270         // NONE
271
272         /*************************** RECORD HANDLER ***************************/
273
274         on_new_record: function(record)
275         {
276             console.log("query_updater on_new_record");
277             console.log(record);
278
279             // if (not and update) {
280
281                 // initial['resource'], initial['lease'] ?
282                 this.initial.push(record);
283
284             //this.set_record_state(record, RECORD_STATE_ATTACHED);
285                 // We simply add to the table
286             // } else {
287                 //                 \ this.initial_resources
288                 //                  \
289                 // this.             \
290                 // current_resources  \    YES    |   NO
291                 // --------------------+----------+---------
292                 //       YES           | attached | added
293                 //       NO            | removed  |   /
294                 // 
295
296             // }
297         },
298
299         // QUERY STATUS
300         //                                      +-----------------+--------------+
301         //                                      v        R        |              |
302         // +-------+  ?G    +-------+        +-------+        +---+---+          |
303         // |       | -----> |       |  !G    |       |        |       |    DA    |
304         // |  ND   |        |  PG   | -----> |   D   | -----> |  PC   | <------+ |
305         // |       | <----- |       |  ~G    |       |   C    |       |        | | 
306         // +-------+   GE   +-------+        +-------+        +-------+      +------+
307         //                                       ^              ^  |         |      |
308         //                                       | DA        UE |  | ?U      | PCA  |
309         //                                       |              |  v         |      |
310         //                                   +-------+        +-------+      +------+
311         //                                   |       |   !U   |       |         ^
312         //                                   |  AD   | <----- |  PU   | --------+
313         //                                   |       |        |       |   ~U     
314         //                                   +-------+        +-------+          
315         //                                                                       
316         //
317         // LEGEND:
318         // 
319         // Plugins (i) receive state information, (ii) perform actions
320         //
321         // States:                                  Actions:
322         // ND : No data                             ?G : Get query
323         // PG : Pending Get                         !G : Get reply  
324         //  D : Data present                        ~G : Get partial reply
325         // PC : Pending changes                     GE : Get error                            
326         // PU : Pending update                       C : Change request
327         // PCA: Pending change with annotation       R : Reset request
328         // AD : Annotated data                      ?U : Update query
329         //                                          !U : Update reply
330         //                                          ~U : Update partial reply
331         //                                          UE : Update error            
332         //                                          DA : Delete annotation request
333         // NOTE:
334         // - D -> PU directly if the user chooses 'dynamic update'
335         // - Be careful for updates if partial Get success
336
337         // ND: No data == initialization state
338         
339         // PG : Pending get
340         // - on_query_in_progress
341         // NOTE: cannot distinguish get and update here. Is it important ?
342
343         on_query_in_progress: function()
344         {
345                 messages.debug("queryupdater.on_query_in_progress");
346             this.spin();
347         },
348
349         // D : Data present
350         // - on_clear_records (Get)
351         // - on_new_record (shared with AD) XXX
352         // - on_query_done
353         // NOTE: cannot distinguish get and update here. Is it important ?
354         // NOTE: Would record key be sufficient for update ?
355
356         on_clear_records: function()
357         {
358             this.clear();
359         },
360
361         on_query_done: function()
362         {
363             console.log("on_query_done");
364             this.unspin();
365         },
366
367         // PC : Pending changes
368         // NOTE: record_key could be sufficient 
369         on_added_record: function(record)
370         {
371             console.log("on_added_record = ",record);
372             this.set_record_state(record, RECORD_STATE_ADDED);
373             // update pending number
374         },
375
376         on_removed_record: function(record_key)
377         {
378             console.log("on_removed_record = ",record_key);
379             this.set_record_state(RECORD_STATE_REMOVED);
380         },
381
382         // PU : Pending update
383         // - on_query_in_progress (already done)
384         
385         // PCA : Pending change with annotation
386         // NOTE: Manifold will inform the plugin about updates, and thus won't
387         // call new record, even if the same channel UUID is used...
388         // - TODO on_updated_record
389         // - Key and confirmation could be sufficient, or key and record state
390         // XXX move record state to the manifold plugin API
391
392         on_field_state_changed: function(result)
393         {
394             console.log("on_field_state_changed");
395             console.log(result);
396             messages.debug(result)
397             /* this.set_state(result.request, result.key, result.value, result.status); */
398             this.set_state(result);
399         },
400
401         // XXX we will have the requests for change
402         // XXX + the requests to move into the query cycle = the buttons aforementioned
403
404         // XXX what happens in case of updates ? not implemented yet
405         // XXX we want resources and leases
406         // listen for SET_ADD and SET_REMOVE for slice query
407
408         /************************** PRIVATE METHODS ***************************/
409
410         _close_click: function(e)
411         {
412             var self = e.data;
413
414             //jQuery.publish('selected', 'add/'+key_value);
415             // this.parentNode is <td> this.parentNode.parentNode is <tr> 
416             // this.parentNode.parentNode.firstChild is the first cell <td> of this line <tr>
417             // this.parentNode.parentNode.firstChild.firstChild is the text in that cell
418             //var firstCellVal=this.parentNode.parentNode.firstChild.firstChild.data;
419             var remove_urn = this.id; 
420             var current_resources = event.data.instance.current_resources;
421             var list_resources = $.grep(current_resources, function(x) {return x.urn != remove_urn});
422             //jQuery.publish('selected', 'cancel/'+this.id+'/'+unfold.get_value(firstCellVal));
423             $.publish('/update-set/' + event.data.instance.options.resource_query_uuid, [list_resources, true]);
424         },
425
426         /******************************** TODO ********************************/
427
428         update_resources: function(resources, change)
429         {
430             messages.debug("update_resources");
431             var my_oTable = this.table.dataTable();
432             var prev_resources = this.current_resources; 
433
434             /*
435              * The first time the query is advertised, don't do anything.  The
436              * component will learn nodes in the slice through the manifest
437              * received through the other subscription 
438              */
439              if (!change)
440                 return;
441              // ioi: Refubrished
442              var initial = this.initial;
443              //var r_removed  = []; //
444              /*-----------------------------------------------------------------------
445                 TODO: remove this dirty hack !!!
446              */
447              resources = jQuery.map(resources, function(x){
448                 if(!('timeslot' in x)){x.timeslot=0;}
449                 return x;
450              });
451              /*
452                 TODO: handle generic keys instead of specific stuff
453                       ex: urn
454                           urn-lease
455              */
456              var initial_urn = $.map(initial, function(x){return x.urn;});
457              var resources_urn = $.map(resources, function(x){return x.urn;});
458              var r_removed = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) == -1 });
459              var r_attached = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) > -1 });
460              var r_added = $.grep(resources, function (x) { return $.inArray(x.urn, initial_urn) == -1 });
461              exists = false; // ioi
462              /*-----------------------------------------------------------------------*/
463
464              my_oTable.fnClearTable();
465              /*
466                 TODO: factorization of this code !!!
467              */
468              $.each(r_added, function(i, r) { 
469                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
470                 var type = 'add';  
471                 // Create the resource objects
472                 // ioi: refubrished
473                 var urn = r.urn;
474                 time = r.timeslot;
475                               
476                 var SPAN = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='"+urn+"'/>";
477                 var slot = "<span id='resource_"+urn+"'>" + time + "</span>"; //ioi
478                 // ioi
479                 var newline=Array();
480                 newline.push(type, urn, slot, SPAN); // ioi
481                 var line = my_oTable.fnAddData(newline);
482                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
483                 nTr.className = type;
484              });
485              $.each(r_attached, function(i, r) {  
486                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
487                 var type = 'attached';
488                 // Create the resource objects
489                 // ioi: refubrished
490                 var node = r.urn;
491                 time = r.timeslot;
492
493                 var SPAN = "<span class='glyphicon glyphicon-renomve ResourceSelectedClose' id='"+node+"'/>";
494                 var slot = "<span id='resource_"+node+"'>" + time + "</span>"; //ioi
495                 // ioi
496                 var newline=Array();
497                 newline.push(type, node, slot, SPAN); // ioi
498                 var line = my_oTable.fnAddData(newline);
499                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
500                 nTr.className = type;
501              });
502              $.each(r_removed, function(i, r) { 
503                 // The list contains objects
504                 // ioi: refubrished
505                 var node = r.urn;
506                 var time = r.timeslot;
507                     
508                 var SPAN = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='"+node+"'/>";
509                 var slot = "<span id='resource_"+node+"'>" + time + "</span>";
510                 // ioi
511                 var newline=Array();
512                 newline.push('remove', node, slot, SPAN); // ioi
513                 var line = my_oTable.fnAddData(newline);
514                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
515                 nTr.className = 'remove';
516              });
517
518              this.current_resources = $.merge(r_attached,r_added);
519
520              /* Allow the user to update the slice */
521              //jQuery('#updateslice-' + data.ResourceSelected.plugin_uuid).prop('disabled', false);
522
523         }, // update_resources
524
525     });
526
527     $.plugin('QueryUpdater', QueryUpdater);
528
529 })(jQuery);