minor updates
[myslice.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                             action = 'ADD';
304                             msg   = 'SUCCESS';
305                             break;
306                         case STATE_SET_IN_FAILURE:
307                             action = 'ADD';
308                             msg   = 'FAILURE';
309                             break;
310
311                         case STATE_SET_OUT_SUCCESS:
312                             action = 'REMOVE';
313                             msg   = 'SUCCESS';
314                             break;
315                         case STATE_SET_OUT_FAILURE:
316                             action = 'REMOVE';
317                             msg   = 'FAILURE';
318                             break;
319
320                     }
321                     break;
322
323                 default:
324                     return;
325             }
326
327             status = msg + status;
328
329             // find line
330             // if no, create it, else replace it
331             // XXX it's not just about adding lines, but sometimes removing some
332             // XXX how do we handle status reset ?
333
334             // Jordan : I don't understand this. I added this test otherwise we have string = ""..."" double quoted twice.
335             if (typeof(data.value) !== "string")
336                 data.value = JSON.stringify(data.value);
337             data.selected_resources = this.selected_resources;
338             row = this.find_row(data.value);
339             newline = [action, data.key, data.value, msg, button];
340             if (!row) {
341                 // XXX second parameter refresh = false can improve performance. todo in querytable also
342                 this.table.fnAddData(newline);
343                 row = this.find_row(data.value);
344             } else {
345                 // Update row text...
346                 this.table.fnUpdate(newline, row.nTr);
347             }
348
349             // Change cell color according to status
350             if (row) {
351                 $(row.nTr).removeClass('add remove')
352                 var cls = action.toLowerCase();
353                 if (cls)
354                     $(row.nTr).addClass(cls);
355             }
356         },
357
358         // XXX we will have the requests for change
359         // XXX + the requests to move into the query cycle = the buttons aforementioned
360
361         // XXX what happens in case of updates ? not implemented yet
362         // XXX we want resources and leases
363         // listen for SET_ADD and SET_REMOVE for slice query
364
365         /************************** PRIVATE METHODS ***************************/
366
367         _close_click: function(e)
368         {
369             var self = e.data;
370
371             //jQuery.publish('selected', 'add/'+key_value);
372             // this.parentNode is <td> this.parentNode.parentNode is <tr> 
373             // this.parentNode.parentNode.firstChild is the first cell <td> of this line <tr>
374             // this.parentNode.parentNode.firstChild.firstChild is the text in that cell
375             //var firstCellVal=this.parentNode.parentNode.firstChild.firstChild.data;
376             var remove_urn = this.id; 
377             var current_resources = event.data.instance.current_resources;
378             var list_resources = $.grep(current_resources, function(x) {return x.urn != remove_urn});
379             //jQuery.publish('selected', 'cancel/'+this.id+'/'+unfold.get_value(firstCellVal));
380             $.publish('/update-set/' + event.data.instance.options.resource_query_uuid, [list_resources, true]);
381         },
382
383         /******************************** TODO ********************************/
384
385         update_resources: function(resources, change)
386         {
387             messages.debug("update_resources");
388             var my_oTable = this.table.dataTable();
389             var prev_resources = this.current_resources; 
390
391             /*
392              * The first time the query is advertised, don't do anything.  The
393              * component will learn nodes in the slice through the manifest
394              * received through the other subscription 
395              */
396              if (!change)
397                 return;
398              // ioi: Refubrished
399              var initial = this.initial;
400              //var r_removed  = []; //
401              /*-----------------------------------------------------------------------
402                 TODO: remove this dirty hack !!!
403              */
404              resources = jQuery.map(resources, function(x){
405                 if(!('timeslot' in x)){x.timeslot=0;}
406                 return x;
407              });
408              /*
409                 TODO: handle generic keys instead of specific stuff
410                       ex: urn
411                           urn-lease
412              */
413              var initial_urn = $.map(initial, function(x){return x.urn;});
414              var resources_urn = $.map(resources, function(x){return x.urn;});
415              var r_removed = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) == -1 });
416              var r_attached = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) > -1 });
417              var r_added = $.grep(resources, function (x) { return $.inArray(x.urn, initial_urn) == -1 });
418              exists = false; // ioi
419              /*-----------------------------------------------------------------------*/
420
421              my_oTable.fnClearTable();
422              /*
423                 TODO: factorization of this code !!!
424              */
425              $.each(r_added, function(i, r) { 
426                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
427                 var type = 'add';  
428                 // Create the resource objects
429                 // ioi: refubrished
430                 var urn = r.urn;
431                 time = r.timeslot;
432                               
433                 var SPAN = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='"+urn+"'/>";
434                 var slot = "<span id='resource_"+urn+"'>" + time + "</span>"; //ioi
435                 // ioi
436                 var newline=Array();
437                 newline.push(type, urn, slot, SPAN); // ioi
438                 var line = my_oTable.fnAddData(newline);
439                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
440                 nTr.className = type;
441              });
442              $.each(r_attached, function(i, r) {  
443                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
444                 var type = 'attached';
445                 // Create the resource objects
446                 // ioi: refubrished
447                 var node = r.urn;
448                 time = r.timeslot;
449
450                 var SPAN = "<span class='glyphicon glyphicon-renomve ResourceSelectedClose' id='"+node+"'/>";
451                 var slot = "<span id='resource_"+node+"'>" + time + "</span>"; //ioi
452                 // ioi
453                 var newline=Array();
454                 newline.push(type, node, slot, SPAN); // ioi
455                 var line = my_oTable.fnAddData(newline);
456                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
457                 nTr.className = type;
458              });
459              $.each(r_removed, function(i, r) { 
460                 // The list contains objects
461                 // ioi: refubrished
462                 var node = r.urn;
463                 var time = r.timeslot;
464                     
465                 var SPAN = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='"+node+"'/>";
466                 var slot = "<span id='resource_"+node+"'>" + time + "</span>";
467                 // ioi
468                 var newline=Array();
469                 newline.push('remove', node, slot, SPAN); // ioi
470                 var line = my_oTable.fnAddData(newline);
471                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
472                 nTr.className = 'remove';
473              });
474
475              this.current_resources = $.merge(r_attached,r_added);
476
477              /* Allow the user to update the slice */
478              //jQuery('#updateslice-' + data.ResourceSelected.plugin_uuid).prop('disabled', false);
479
480         }, // update_resources
481
482     });
483
484     $.plugin('ApplyPlugin', ApplyPlugin);
485
486 })(jQuery);