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