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