Manifold folder removed from inside myslice, should not be located there
[unfold.git] / plugins / queryupdater / static / js / queryupdater.js
1 /**
2  * MySlice QueryUpdater 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 QueryUpdater = Plugin.extend({
30
31         init: function(options, element) {
32                 this.classname="queryupdater";
33             this._super(options, element);
34
35             var self = this;
36
37             this.initial = Array();
38
39             this.table = this.elmt('table').dataTable({
40 // the original querytable layout was
41 //                sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
42 // however the bottom line with 'showing blabla...' and the navigation widget are not really helpful
43                 sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t>",
44 // so this does not matter anymore now that the pagination area is turned off
45 //                sPaginationType: 'bootstrap',
46                 bAutoWidth: true,
47 //                bJQueryUI      : true,
48 //                bRetrieve      : true,
49 //                sScrollX       : '100%',                 // Horizontal scrolling 
50 //                bSortClasses   : false,              // Disable style for the sorted column
51 //                aaSorting      : [[ 0, 'asc' ]],        // Default sorting on URN
52 //                fnDrawCallback: function() {      // Reassociate close click every time the table is redrawn
53 //                    /* Prevent to loop on click while redrawing table  */
54 //                    $('.ResourceSelectedClose').unbind('click');
55 //                    /* Handle clicks on close span */
56 //                    /* Reassociate close click every time the table is redrawn */
57 //                    $('.ResourceSelectedClose').bind('click', self, self._close_click);
58 //                }
59              });
60             
61             // XXX This should not be done at init...
62             this.elmt('update').click(this, this.do_checksla);
63             this.elmt('refresh').click(this, this.do_refresh);
64             this.elmt('reset').click(this, this.do_reset);
65             this.elmt('clear_annotations').click(this, this.do_clear_annotations);
66
67             this.listen_query(options.query_uuid);
68         },
69
70         /*************************** PLUGIN EVENTS ****************************/
71
72         /***************************** GUI EVENTS *****************************/
73
74         do_checksla: function(e) {
75             var username = e.data.options.username;
76             var urn = data.value;
77             // XXX check that the query is not disabled
78
79             console.log("DATA VALUE: " + data.value);
80
81             if (data.value.toLowerCase().indexOf("iminds") >= 0){
82
83                 $('#sla_dialog').show();
84                 $('#slamodal').modal('show');
85                 
86                 $(document).ready(function() {
87                     $("#accept_sla").click(function(){
88                         console.log("SLA ACCEPTED");
89                         console.log("With username: " + username);
90                         if(urn.toLowerCase().indexOf("wall2") >= 0){ 
91                             $.post("/sla/agreements/simplecreate", 
92                                 { "template_id": "iMindsServiceVirtualwall",
93                                   "user": username,
94                                   "expiration_time": new Date() // jgarcia: FIXME
95                                 });
96                         } else if(urn.toLowerCase().indexOf("wilab2") >= 0){
97                             $.post("/sla/agreements/simplecreate", 
98                                 { "template_id":"iMindsServiceWiLab2",
99                                   "user":username,
100                                   "expiration_time": new Date() // jgarcia: FIXME
101                                 });
102                         }
103                         $('#slamodal').modal('hide');
104                         self.spin();
105                         console.log("Executing do_update after sending SLA");
106                         // XXX check that the query is not disabled
107                         manifold.raise_event(self.options.query_uuid, RUN_UPDATE);
108
109                         // how to stop the spinning after the event? 
110                         // this should be triggered by some on_updatequery_done ?
111                     }); 
112                 });
113
114                 $(document).ready(function() {
115                     $("#dismiss_sla").click(function(){
116                         console.log("SLA NOT ACCEPTED");
117                         $('#slamodal').modal('hide');
118                     }); 
119                 });
120
121             } else {
122                 self.spin();
123                 console.log("do_update");
124                 // XXX check that the query is not disabled
125                 manifold.raise_event(self.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_update: function(e) {
133             var self = e.data;
134
135             var username = e.data.options.username;
136             var urn = data.value;
137             // XXX check that the query is not disabled
138
139             console.log("DATA VALUE: " + data.value);
140
141             if (data.value.toLowerCase().indexOf("iminds") >= 0){
142
143                 $('#sla_dialog').show();
144                 $('#slamodal').modal('show');
145                 
146                 $(document).ready(function() {
147                     $("#accept_sla").click(function(){
148                         console.log("SLA ACCEPTED");
149                         console.log("With username: " + username);
150                         if(urn.toLowerCase().indexOf("wall2") >= 0){ 
151                             $.post("/sla/agreements/simplecreate", 
152                                 { "template_id": "iMindsServiceVirtualwall",
153                                   "user": username,
154                                   "expiration_time": new Date() // jgarcia: FIXME
155                                 });
156                         } else if(urn.toLowerCase().indexOf("wilab2") >= 0){
157                             $.post("/sla/agreements/simplecreate", 
158                                 { "template_id":"iMindsServiceWiLab2",
159                                   "user":username,
160                                   "expiration_time": new Date() // jgarcia: FIXME
161                                 });
162                         }
163                         $('#slamodal').modal('hide');
164                         self.spin();
165                         console.log("Executing do_update after sending SLA");
166                         // XXX check that the query is not disabled
167                         manifold.raise_event(self.options.query_uuid, RUN_UPDATE);
168
169                         // how to stop the spinning after the event? 
170                         // this should be triggered by some on_updatequery_done ?
171                     }); 
172                 });
173
174                 $(document).ready(function() {
175                     $("#dismiss_sla").click(function(){
176                         console.log("SLA NOT ACCEPTED");
177                         $('#slamodal').modal('hide');
178                     }); 
179                 });
180
181             } else {
182                 self.spin();
183                 console.log("do_update");
184                 // XXX check that the query is not disabled
185                 manifold.raise_event(self.options.query_uuid, RUN_UPDATE);
186
187                 // how to stop the spinning after the event? 
188                 // this should be triggered by some on_updatequery_done ?
189             }
190
191         },
192
193         // related buttons are also disabled in the html template
194         do_refresh: function(e)
195         {
196             throw 'resource_selected.do_refresh Not implemented';
197         },
198
199         do_reset: function(e)
200         {
201             throw 'queryupdater.do_reset Not implemented';
202         },
203
204         do_clear_annotations: function(e)
205         {
206             throw 'queryupdater.do_clear_annotations Not implemented';
207         },
208         
209         /************************** GUI MANIPULATION **************************/
210
211         
212         set_button_state: function(name, state)
213         {
214             this.elmt(name).attr('disabled', state ? false : 'disabled');
215         },
216
217         clear: function()
218         {
219
220         },
221
222         find_row: function(key)
223         {
224             // key in third position, column id = 2
225             var KEY_POS = 2;
226
227             var cols = $.grep(this.table.fnSettings().aoData, function(col) {
228                 return (col._aData[KEY_POS] == key);
229             } );
230
231             if (cols.length == 0)
232                 return null;
233             if (cols.length > 1)
234                 throw "Too many same-key rows in ResourceSelected plugin";
235
236             return cols[0];
237         },
238
239         set_state: function(data)
240         {
241             console.log("function set_state");
242             var action;
243             var msg;
244             var button = '';
245
246             var row;
247             
248             // make sure the change is visible : toggle on the whole plugin
249             // this might have to be made an 'auto-toggle' option of this plugin..
250             // also it might be needed to be a little finer-grained here
251
252         // XXX we don't want to show automaticaly the pending when a checkbox is checked
253             //this.toggle_on();
254             
255             switch(data.request) {
256                 case FIELD_REQUEST_ADD_RESET:
257                 case FIELD_REQUEST_REMOVE_RESET:
258                     // find line and delete it
259                     row = this.find_row(data.value);
260                     if (row)
261                         this.table.fnDeleteRow(row.nTr);
262                         $("#badge-pending").data('number', $("#badge-pending").data('number') - 1 );
263                         $("#badge-pending").text($("#badge-pending").data('number'));
264                     return;
265                 case FIELD_REQUEST_CHANGE:
266                     action = 'UPDATE';
267                     break;
268                 case FIELD_REQUEST_ADD:
269                     action = 'ADD';
270                     break;
271                 case FIELD_REQUEST_REMOVE:
272                     action = 'REMOVE';
273                     break;
274             }
275
276             switch(data.status) {
277                 case FIELD_REQUEST_PENDING:
278                     msg   = 'PENDING';
279                     button = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='" + data.key + "'/>";
280                     break;
281                 case FIELD_REQUEST_SUCCESS:
282                     msg   = 'SUCCESS';
283                     break;
284                 case FIELD_REQUEST_FAILURE:
285                     msg   = 'FAILURE';
286                     break;
287             }
288
289             var status = msg + status;
290
291             
292
293             // find line
294             // if no, create it, else replace it
295             // XXX it's not just about adding lines, but sometimes removing some
296             // XXX how do we handle status reset ?
297             data.value = JSON.stringify(data.value);
298             row = this.find_row(data.value);
299             newline = [
300                 action,
301                 data.key,
302                 data.value,
303                 msg,
304                 button
305             ];
306             if (!row) {
307                 // XXX second parameter refresh = false can improve performance. todo in querytable also
308                 this.table.fnAddData(newline);
309                 row = this.find_row(data.value);
310                 $("#badge-pending").data('number', $("#badge-pending").data('number') + 1 );
311                 $("#badge-pending").text($("#badge-pending").data('number'));
312             } else {
313                 // Update row text...
314                 this.table.fnUpdate(newline, row.nTr);
315             }
316
317             // Change cell color according to status
318             if (row) {
319                 $(row.nTr).removeClass('add remove')
320                 var cls = action.toLowerCase();
321                 if (cls)
322                     $(row.nTr).addClass(cls);
323             }
324         },
325
326         /*************************** QUERY HANDLER ****************************/
327
328         // NONE
329
330         /*************************** RECORD HANDLER ***************************/
331
332         on_new_record: function(record)
333         {
334             console.log("query_updater on_new_record");
335             console.log(record);
336
337             // if (not and update) {
338
339                 // initial['resource'], initial['lease'] ?
340                 this.initial.push(record);
341
342             //this.set_record_state(record, RECORD_STATE_ATTACHED);
343                 // We simply add to the table
344             // } else {
345                 //                 \ this.initial_resources
346                 //                  \
347                 // this.             \
348                 // current_resources  \    YES    |   NO
349                 // --------------------+----------+---------
350                 //       YES           | attached | added
351                 //       NO            | removed  |   /
352                 // 
353
354             // }
355         },
356
357         // QUERY STATUS
358         //                                      +-----------------+--------------+
359         //                                      v        R        |              |
360         // +-------+  ?G    +-------+        +-------+        +---+---+          |
361         // |       | -----> |       |  !G    |       |        |       |    DA    |
362         // |  ND   |        |  PG   | -----> |   D   | -----> |  PC   | <------+ |
363         // |       | <----- |       |  ~G    |       |   C    |       |        | | 
364         // +-------+   GE   +-------+        +-------+        +-------+      +------+
365         //                                       ^              ^  |         |      |
366         //                                       | DA        UE |  | ?U      | PCA  |
367         //                                       |              |  v         |      |
368         //                                   +-------+        +-------+      +------+
369         //                                   |       |   !U   |       |         ^
370         //                                   |  AD   | <----- |  PU   | --------+
371         //                                   |       |        |       |   ~U     
372         //                                   +-------+        +-------+          
373         //                                                                       
374         //
375         // LEGEND:
376         // 
377         // Plugins (i) receive state information, (ii) perform actions
378         //
379         // States:                                  Actions:
380         // ND : No data                             ?G : Get query
381         // PG : Pending Get                         !G : Get reply  
382         //  D : Data present                        ~G : Get partial reply
383         // PC : Pending changes                     GE : Get error                            
384         // PU : Pending update                       C : Change request
385         // PCA: Pending change with annotation       R : Reset request
386         // AD : Annotated data                      ?U : Update query
387         //                                          !U : Update reply
388         //                                          ~U : Update partial reply
389         //                                          UE : Update error            
390         //                                          DA : Delete annotation request
391         // NOTE:
392         // - D -> PU directly if the user chooses 'dynamic update'
393         // - Be careful for updates if partial Get success
394
395         // ND: No data == initialization state
396         
397         // PG : Pending get
398         // - on_query_in_progress
399         // NOTE: cannot distinguish get and update here. Is it important ?
400
401         on_query_in_progress: function()
402         {
403                 messages.debug("queryupdater.on_query_in_progress");
404             this.spin();
405         },
406
407         // D : Data present
408         // - on_clear_records (Get)
409         // - on_new_record (shared with AD) XXX
410         // - on_query_done
411         // NOTE: cannot distinguish get and update here. Is it important ?
412         // NOTE: Would record key be sufficient for update ?
413
414         on_clear_records: function()
415         {
416             this.clear();
417         },
418
419         on_query_done: function()
420         {
421             console.log("on_query_done");
422             this.unspin();
423         },
424
425         // PC : Pending changes
426         // NOTE: record_key could be sufficient 
427         on_added_record: function(record)
428         {
429             console.log("on_added_record = ",record);
430             this.set_record_state(record, RECORD_STATE_ADDED);
431             // update pending number
432         },
433
434         on_removed_record: function(record_key)
435         {
436             console.log("on_removed_record = ",record_key);
437             this.set_record_state(RECORD_STATE_REMOVED);
438         },
439
440         // PU : Pending update
441         // - on_query_in_progress (already done)
442         
443         // PCA : Pending change with annotation
444         // NOTE: Manifold will inform the plugin about updates, and thus won't
445         // call new record, even if the same channel UUID is used...
446         // - TODO on_updated_record
447         // - Key and confirmation could be sufficient, or key and record state
448         // XXX move record state to the manifold plugin API
449
450         on_field_state_changed: function(result)
451         {
452             console.log("on_field_state_changed");
453             console.log(result);
454             messages.debug(result)
455             /* this.set_state(result.request, result.key, result.value, result.status); */
456             this.set_state(result);
457         },
458
459         // XXX we will have the requests for change
460         // XXX + the requests to move into the query cycle = the buttons aforementioned
461
462         // XXX what happens in case of updates ? not implemented yet
463         // XXX we want resources and leases
464         // listen for SET_ADD and SET_REMOVE for slice query
465
466         /************************** PRIVATE METHODS ***************************/
467
468         _close_click: function(e)
469         {
470             var self = e.data;
471
472             //jQuery.publish('selected', 'add/'+key_value);
473             // this.parentNode is <td> this.parentNode.parentNode is <tr> 
474             // this.parentNode.parentNode.firstChild is the first cell <td> of this line <tr>
475             // this.parentNode.parentNode.firstChild.firstChild is the text in that cell
476             //var firstCellVal=this.parentNode.parentNode.firstChild.firstChild.data;
477             var remove_urn = this.id; 
478             var current_resources = event.data.instance.current_resources;
479             var list_resources = $.grep(current_resources, function(x) {return x.urn != remove_urn});
480             //jQuery.publish('selected', 'cancel/'+this.id+'/'+unfold.get_value(firstCellVal));
481             $.publish('/update-set/' + event.data.instance.options.resource_query_uuid, [list_resources, true]);
482         },
483
484         /******************************** TODO ********************************/
485
486         update_resources: function(resources, change)
487         {
488             messages.debug("update_resources");
489             var my_oTable = this.table.dataTable();
490             var prev_resources = this.current_resources; 
491
492             /*
493              * The first time the query is advertised, don't do anything.  The
494              * component will learn nodes in the slice through the manifest
495              * received through the other subscription 
496              */
497              if (!change)
498                 return;
499              // ioi: Refubrished
500              var initial = this.initial;
501              //var r_removed  = []; //
502              /*-----------------------------------------------------------------------
503                 TODO: remove this dirty hack !!!
504              */
505              resources = jQuery.map(resources, function(x){
506                 if(!('timeslot' in x)){x.timeslot=0;}
507                 return x;
508              });
509              /*
510                 TODO: handle generic keys instead of specific stuff
511                       ex: urn
512                           urn-lease
513              */
514              var initial_urn = $.map(initial, function(x){return x.urn;});
515              var resources_urn = $.map(resources, function(x){return x.urn;});
516              var r_removed = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) == -1 });
517              var r_attached = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) > -1 });
518              var r_added = $.grep(resources, function (x) { return $.inArray(x.urn, initial_urn) == -1 });
519              exists = false; // ioi
520              /*-----------------------------------------------------------------------*/
521
522              my_oTable.fnClearTable();
523              /*
524                 TODO: factorization of this code !!!
525              */
526              $.each(r_added, function(i, r) { 
527                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
528                 var type = 'add';  
529                 // Create the resource objects
530                 // ioi: refubrished
531                 var urn = r.urn;
532                 time = r.timeslot;
533                               
534                 var SPAN = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='"+urn+"'/>";
535                 var slot = "<span id='resource_"+urn+"'>" + time + "</span>"; //ioi
536                 // ioi
537                 var newline=Array();
538                 newline.push(type, urn, slot, SPAN); // ioi
539                 var line = my_oTable.fnAddData(newline);
540                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
541                 nTr.className = type;
542              });
543              $.each(r_attached, function(i, r) {  
544                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
545                 var type = 'attached';
546                 // Create the resource objects
547                 // ioi: refubrished
548                 var node = r.urn;
549                 time = r.timeslot;
550
551                 var SPAN = "<span class='glyphicon glyphicon-renomve ResourceSelectedClose' id='"+node+"'/>";
552                 var slot = "<span id='resource_"+node+"'>" + time + "</span>"; //ioi
553                 // ioi
554                 var newline=Array();
555                 newline.push(type, node, slot, SPAN); // ioi
556                 var line = my_oTable.fnAddData(newline);
557                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
558                 nTr.className = type;
559              });
560              $.each(r_removed, function(i, r) { 
561                 // The list contains objects
562                 // ioi: refubrished
563                 var node = r.urn;
564                 var time = r.timeslot;
565                     
566                 var SPAN = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='"+node+"'/>";
567                 var slot = "<span id='resource_"+node+"'>" + time + "</span>";
568                 // ioi
569                 var newline=Array();
570                 newline.push('remove', node, slot, SPAN); // ioi
571                 var line = my_oTable.fnAddData(newline);
572                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
573                 nTr.className = 'remove';
574              });
575
576              this.current_resources = $.merge(r_attached,r_added);
577
578              /* Allow the user to update the slice */
579              //jQuery('#updateslice-' + data.ResourceSelected.plugin_uuid).prop('disabled', false);
580
581         }, // update_resources
582
583     });
584
585     $.plugin('QueryUpdater', QueryUpdater);
586
587 })(jQuery);