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