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