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