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