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