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