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