fed4fire review changes
[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             self.spin();
78             console.log("do_update");
79
80             // XXX check that the query is not disabled
81             manifold.raise_event(self.options.query_uuid, RUN_UPDATE);
82
83             // how to stop the spinning after the event? 
84             // this should be triggered by some on_updatequery_done ?
85         },
86
87         // related buttons are also disabled in the html template
88         do_refresh: function(e)
89         {
90             throw 'resource_selected.do_refresh Not implemented';
91         },
92
93         do_reset: function(e)
94         {
95             throw 'queryupdater.do_reset Not implemented';
96         },
97
98         do_clear_annotations: function(e)
99         {
100             throw 'queryupdater.do_clear_annotations Not implemented';
101         },
102         
103         /************************** GUI MANIPULATION **************************/
104
105         
106         set_button_state: function(name, state)
107         {
108             this.elmt(name).attr('disabled', state ? false : 'disabled');
109         },
110
111         clear: function()
112         {
113
114         },
115
116         find_row: function(key)
117         {
118             // key in third position, column id = 2
119             var KEY_POS = 2;
120
121             var cols = $.grep(this.table.fnSettings().aoData, function(col) {
122                 return (col._aData[KEY_POS] == key);
123             } );
124
125             if (cols.length == 0)
126                 return null;
127             if (cols.length > 1)
128                 throw "Too many same-key rows in ResourceSelected plugin";
129
130             return cols[0];
131         },
132
133         set_state: function(data)
134         {
135             console.log("function set_state");
136             var action;
137             var msg;
138             var button = '';
139
140             var row;
141             
142             // make sure the change is visible : toggle on the whole plugin
143             // this might have to be made an 'auto-toggle' option of this plugin..
144             // also it might be needed to be a little finer-grained here
145
146         // XXX we don't want to show automaticaly the pending when a checkbox is checked
147             //this.toggle_on();
148             
149             switch(data.request) {
150                 case FIELD_REQUEST_ADD_RESET:
151                 case FIELD_REQUEST_REMOVE_RESET:
152                     // find line and delete it
153                     row = this.find_row(data.value);
154                     if (row)
155                         this.table.fnDeleteRow(row.nTr);
156                         $("#badge-pending").data('number', $("#badge-pending").data('number') - 1 );
157                         $("#badge-pending").text($("#badge-pending").data('number'));
158                     return;
159                 case FIELD_REQUEST_CHANGE:
160                     action = 'UPDATE';
161                     break;
162                 case FIELD_REQUEST_ADD:
163                     action = 'ADD';
164                     break;
165                 case FIELD_REQUEST_REMOVE:
166                     action = 'REMOVE';
167                     break;
168             }
169
170             switch(data.status) {
171                 case FIELD_REQUEST_PENDING:
172                     msg   = 'PENDING';
173                     button = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='" + data.key + "'/>";
174                     break;
175                 case FIELD_REQUEST_SUCCESS:
176                     msg   = 'SUCCESS';
177                     break;
178                 case FIELD_REQUEST_FAILURE:
179                     msg   = 'FAILURE';
180                     break;
181             }
182
183             var status = msg + status;
184
185             
186
187             // find line
188             // if no, create it, else replace it
189             // XXX it's not just about adding lines, but sometimes removing some
190             // XXX how do we handle status reset ?
191             data.value = JSON.stringify(data.value);
192             row = this.find_row(data.value);
193             newline = [
194                 action,
195                 data.key,
196                 data.value,
197                 msg,
198                 button
199             ];
200             if (!row) {
201                 // XXX second parameter refresh = false can improve performance. todo in querytable also
202                 this.table.fnAddData(newline);
203                 row = this.find_row(data.value);
204                 $("#badge-pending").data('number', $("#badge-pending").data('number') + 1 );
205                 $("#badge-pending").text($("#badge-pending").data('number'));
206             } else {
207                 // Update row text...
208                 this.table.fnUpdate(newline, row.nTr);
209             }
210
211             // Change cell color according to status
212             if (row) {
213                 $(row.nTr).removeClass('add remove')
214                 var cls = action.toLowerCase();
215                 if (cls)
216                     $(row.nTr).addClass(cls);
217             }
218         },
219
220         /*************************** QUERY HANDLER ****************************/
221
222         // NONE
223
224         /*************************** RECORD HANDLER ***************************/
225
226         on_new_record: function(record)
227         {
228             console.log("query_updater on_new_record");
229             console.log(record);
230
231             // if (not and update) {
232
233                 // initial['resource'], initial['lease'] ?
234                 this.initial.push(record);
235
236             //this.set_record_state(record, RECORD_STATE_ATTACHED);
237                 // We simply add to the table
238             // } else {
239                 //                 \ this.initial_resources
240                 //                  \
241                 // this.             \
242                 // current_resources  \    YES    |   NO
243                 // --------------------+----------+---------
244                 //       YES           | attached | added
245                 //       NO            | removed  |   /
246                 // 
247
248             // }
249         },
250
251         // QUERY STATUS
252         //                                      +-----------------+--------------+
253         //                                      v        R        |              |
254         // +-------+  ?G    +-------+        +-------+        +---+---+          |
255         // |       | -----> |       |  !G    |       |        |       |    DA    |
256         // |  ND   |        |  PG   | -----> |   D   | -----> |  PC   | <------+ |
257         // |       | <----- |       |  ~G    |       |   C    |       |        | | 
258         // +-------+   GE   +-------+        +-------+        +-------+      +------+
259         //                                       ^              ^  |         |      |
260         //                                       | DA        UE |  | ?U      | PCA  |
261         //                                       |              |  v         |      |
262         //                                   +-------+        +-------+      +------+
263         //                                   |       |   !U   |       |         ^
264         //                                   |  AD   | <----- |  PU   | --------+
265         //                                   |       |        |       |   ~U     
266         //                                   +-------+        +-------+          
267         //                                                                       
268         //
269         // LEGEND:
270         // 
271         // Plugins (i) receive state information, (ii) perform actions
272         //
273         // States:                                  Actions:
274         // ND : No data                             ?G : Get query
275         // PG : Pending Get                         !G : Get reply  
276         //  D : Data present                        ~G : Get partial reply
277         // PC : Pending changes                     GE : Get error                            
278         // PU : Pending update                       C : Change request
279         // PCA: Pending change with annotation       R : Reset request
280         // AD : Annotated data                      ?U : Update query
281         //                                          !U : Update reply
282         //                                          ~U : Update partial reply
283         //                                          UE : Update error            
284         //                                          DA : Delete annotation request
285         // NOTE:
286         // - D -> PU directly if the user chooses 'dynamic update'
287         // - Be careful for updates if partial Get success
288
289         // ND: No data == initialization state
290         
291         // PG : Pending get
292         // - on_query_in_progress
293         // NOTE: cannot distinguish get and update here. Is it important ?
294
295         on_query_in_progress: function()
296         {
297                 messages.debug("queryupdater.on_query_in_progress");
298             this.spin();
299         },
300
301         // D : Data present
302         // - on_clear_records (Get)
303         // - on_new_record (shared with AD) XXX
304         // - on_query_done
305         // NOTE: cannot distinguish get and update here. Is it important ?
306         // NOTE: Would record key be sufficient for update ?
307
308         on_clear_records: function()
309         {
310             this.clear();
311         },
312
313         on_query_done: function()
314         {
315             console.log("on_query_done");
316             this.unspin();
317         },
318
319         // PC : Pending changes
320         // NOTE: record_key could be sufficient 
321         on_added_record: function(record)
322         {
323             console.log("on_added_record = ",record);
324             this.set_record_state(record, RECORD_STATE_ADDED);
325             // update pending number
326         },
327
328         on_removed_record: function(record_key)
329         {
330             console.log("on_removed_record = ",record_key);
331             this.set_record_state(RECORD_STATE_REMOVED);
332         },
333
334         // PU : Pending update
335         // - on_query_in_progress (already done)
336         
337         // PCA : Pending change with annotation
338         // NOTE: Manifold will inform the plugin about updates, and thus won't
339         // call new record, even if the same channel UUID is used...
340         // - TODO on_updated_record
341         // - Key and confirmation could be sufficient, or key and record state
342         // XXX move record state to the manifold plugin API
343
344         on_field_state_changed: function(result)
345         {
346             console.log("on_field_state_changed");
347             console.log(result);
348             messages.debug(result)
349             /* this.set_state(result.request, result.key, result.value, result.status); */
350             this.set_state(result);
351         },
352
353         // XXX we will have the requests for change
354         // XXX + the requests to move into the query cycle = the buttons aforementioned
355
356         // XXX what happens in case of updates ? not implemented yet
357         // XXX we want resources and leases
358         // listen for SET_ADD and SET_REMOVE for slice query
359
360         /************************** PRIVATE METHODS ***************************/
361
362         _close_click: function(e)
363         {
364             var self = e.data;
365
366             //jQuery.publish('selected', 'add/'+key_value);
367             // this.parentNode is <td> this.parentNode.parentNode is <tr> 
368             // this.parentNode.parentNode.firstChild is the first cell <td> of this line <tr>
369             // this.parentNode.parentNode.firstChild.firstChild is the text in that cell
370             //var firstCellVal=this.parentNode.parentNode.firstChild.firstChild.data;
371             var remove_urn = this.id; 
372             var current_resources = event.data.instance.current_resources;
373             var list_resources = $.grep(current_resources, function(x) {return x.urn != remove_urn});
374             //jQuery.publish('selected', 'cancel/'+this.id+'/'+unfold.get_value(firstCellVal));
375             $.publish('/update-set/' + event.data.instance.options.resource_query_uuid, [list_resources, true]);
376         },
377
378         /******************************** TODO ********************************/
379
380         update_resources: function(resources, change)
381         {
382             messages.debug("update_resources");
383             var my_oTable = this.table.dataTable();
384             var prev_resources = this.current_resources; 
385
386             /*
387              * The first time the query is advertised, don't do anything.  The
388              * component will learn nodes in the slice through the manifest
389              * received through the other subscription 
390              */
391              if (!change)
392                 return;
393              // ioi: Refubrished
394              var initial = this.initial;
395              //var r_removed  = []; //
396              /*-----------------------------------------------------------------------
397                 TODO: remove this dirty hack !!!
398              */
399              resources = jQuery.map(resources, function(x){
400                 if(!('timeslot' in x)){x.timeslot=0;}
401                 return x;
402              });
403              /*
404                 TODO: handle generic keys instead of specific stuff
405                       ex: urn
406                           urn-lease
407              */
408              var initial_urn = $.map(initial, function(x){return x.urn;});
409              var resources_urn = $.map(resources, function(x){return x.urn;});
410              var r_removed = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) == -1 });
411              var r_attached = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) > -1 });
412              var r_added = $.grep(resources, function (x) { return $.inArray(x.urn, initial_urn) == -1 });
413              exists = false; // ioi
414              /*-----------------------------------------------------------------------*/
415
416              my_oTable.fnClearTable();
417              /*
418                 TODO: factorization of this code !!!
419              */
420              $.each(r_added, function(i, r) { 
421                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
422                 var type = 'add';  
423                 // Create the resource objects
424                 // ioi: refubrished
425                 var urn = r.urn;
426                 time = r.timeslot;
427                               
428                 var SPAN = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='"+urn+"'/>";
429                 var slot = "<span id='resource_"+urn+"'>" + time + "</span>"; //ioi
430                 // ioi
431                 var newline=Array();
432                 newline.push(type, urn, slot, SPAN); // ioi
433                 var line = my_oTable.fnAddData(newline);
434                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
435                 nTr.className = type;
436              });
437              $.each(r_attached, function(i, r) {  
438                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
439                 var type = 'attached';
440                 // Create the resource objects
441                 // ioi: refubrished
442                 var node = r.urn;
443                 time = r.timeslot;
444
445                 var SPAN = "<span class='glyphicon glyphicon-renomve ResourceSelectedClose' id='"+node+"'/>";
446                 var slot = "<span id='resource_"+node+"'>" + time + "</span>"; //ioi
447                 // ioi
448                 var newline=Array();
449                 newline.push(type, node, slot, SPAN); // ioi
450                 var line = my_oTable.fnAddData(newline);
451                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
452                 nTr.className = type;
453              });
454              $.each(r_removed, function(i, r) { 
455                 // The list contains objects
456                 // ioi: refubrished
457                 var node = r.urn;
458                 var time = r.timeslot;
459                     
460                 var SPAN = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='"+node+"'/>";
461                 var slot = "<span id='resource_"+node+"'>" + time + "</span>";
462                 // ioi
463                 var newline=Array();
464                 newline.push('remove', node, slot, SPAN); // ioi
465                 var line = my_oTable.fnAddData(newline);
466                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
467                 nTr.className = 'remove';
468              });
469
470              this.current_resources = $.merge(r_attached,r_added);
471
472              /* Allow the user to update the slice */
473              //jQuery('#updateslice-' + data.ResourceSelected.plugin_uuid).prop('disabled', false);
474
475         }, // update_resources
476
477     });
478
479     $.plugin('QueryUpdater', QueryUpdater);
480
481 })(jQuery);