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