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