plugins: updated query_editor
[myslice.git] / plugins / resources_selected / resources_selected.js
1 /**
2  * MySlice ResourcesSelected 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 /*
13  * It's a best practice to pass jQuery to an IIFE (Immediately Invoked Function
14  * Expression) that maps it to the dollar sign so it can't be overwritten by
15  * another library in the scope of its execution.
16  */
17 (function( $ ){
18
19     var PLUGIN_NAME = 'ResourcesSelected';
20
21     // Routing calls
22     jQuery.fn.ResourcesSelected = function( method ) {
23         if ( methods[method] ) {
24             return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
25         } else if ( typeof method === 'object' || ! method ) {
26             return methods.init.apply( this, arguments );
27         } else {
28             jQuery.error( 'Method ' +  method + ' does not exist on jQuery.' + PLUGIN_NAME );
29         }    
30
31     };
32
33     /***************************************************************************
34      * Public methods
35      ***************************************************************************/
36
37     var methods = {
38
39         /**
40          * @brief Plugin initialization
41          * @param options : an associative array of setting values
42          * @return : a jQuery collection of objects on which the plugin is
43          *     applied, which allows to maintain chainability of calls
44          */
45         init : function( options ) {
46
47             return this.each(function(){
48
49                 var $this = $(this);
50
51                 /* An object that will hold private variables and methods */
52                 var plugin = new ResourcesSelected(options);
53                 $(this).data('Manifold', plugin);
54
55                 //$this.set_query_handler(options.query_uuid, hazelnut.query_handler);
56                 //$this.set_record_handler(options.query_uuid, hazelnut.record_handler); 
57
58                 //var RESULTS_RESOURCES = '/results/' + options.resource_query_uuid + '/changed';
59                 //var UPDATE_RESOURCES  = '/update-set/' + options.resource_query_uuid;
60                 //$.subscribe(RESULTS_RESOURCES, function(e, resources) { s.set_resources(resources);    });
61                 //$.subscribe(UPDATE_RESOURCES,  function(e, resources, change) { s.update_resources(resources, change); });
62                 
63             }); // this.each
64         }, // init
65
66         /**
67          * @brief Plugin destruction
68          * @return : a jQuery collection of objects on which the plugin is
69          *     applied, which allows to maintain chainability of calls
70          */
71         destroy : function( ) {
72
73             return this.each(function() {
74                 var $this = $(this);
75                 var plugin = $this.data('Manifold');
76
77                 // Remove associated data
78                 plugin.remove();
79                 $this.removeData('Manifold');
80             });
81         }, // destroy
82
83     }; // var methods
84
85     /***************************************************************************
86      * Plugin object
87      ***************************************************************************/
88
89     function ResourcesSelected(options)
90     {
91         /* member variables */
92         this.options = options;
93         var object = this;
94
95         /* The resources that are in the slice */
96         this.current_resources = null;
97
98         /* The resources that are in the slice before any edit */
99         this.initial_resources = null;
100
101         var rs = this;
102
103         /* constructor */
104             // ioi: resources table id
105         var TABLE_NAME = '#table-' + options.plugin_uuid;
106         this.table = $(TABLE_NAME).dataTable({
107             //sPaginationType: 'full_numbers',  // Use pagination
108             sPaginationType: 'bootstrap',
109             //bJQueryUI: true,
110             //bRetrieve: true,
111             sScrollX: '100%',                 // Horizontal scrolling 
112             bSortClasses: false,              // Disable style for the sorted column
113             aaSorting: [[ 1, "asc" ]],        // Default sorting on URN
114             fnDrawCallback: function() {      // Reassociate close click every time the table is redrawn
115                 /* Prevent to loop on click while redrawing table  */
116                 jQuery('.ResourceSelectedClose').unbind('click');
117                 /* Handle clicks on close span */
118                 /* Reassociate close click every time the table is redrawn */
119                 $('.ResourceSelectedClose').bind('click',{instance: rs}, object.close_click);
120             }
121          });
122
123         /* methods */
124
125         this.set_resources = function(resources)
126         {
127             console.log("set_resources");
128             /* Some sanity checks on the API results */
129             if(resources.length==0){
130                 this.table.html(errorDisplay("No Result"));   
131                 return;
132             }
133
134             if (typeof(resources[0].error) != 'undefined') {
135                 this.table.html(errorDisplay(resources[0].error));
136                 return;
137             }
138
139             /* Update the table with resources in the slice */
140             //var slivers = $.grep(resources, function(i) {return typeof(i['sliver']) != 'undefined';})
141             var slivers = resources;
142             var sliver_urns = Array();
143             // ioi : refubrished
144                 $.each(resources, function(i, x) { sliver_urns.push({urn:x.urn, timeslot:"0"}); }); // ioi
145
146             this.initial_resources = sliver_urns; // We make a copy of the object // ioi
147                 // ioi
148             
149             if (this.current_resources == null) {
150                 this.current_resources = sliver_urns;
151
152                 /* We simply add to the ResourceSelected table */
153                 var newlines=Array();
154                 $.each(sliver_urns, function(index, elt) {
155                     newlines.push(Array('attached', elt.urn, elt.timeslot, "<span class='ui-icon ui-icon-close ResourceSelectedClose' id='"+elt.urn+"'/>")); // ioi: added last element
156                 });
157                 this.table.dataTable().fnAddData(newlines);
158             } else {
159                 alert('Slice updated. Refresh not yet implemented!');
160             }
161         }
162
163         this.update_resources = function(resources, change) {
164             console.log("update_resources");
165             var my_oTable = this.table.dataTable();
166             var prev_resources = this.current_resources; 
167             /*      \ this.initial_resources
168              *           \
169              * this.          \
170              * current_resources  \    YES    |   NO
171              * --------------------+----------+---------
172              *       YES           | attached | added
173              *       NO            | removed  |   /
174              */
175
176             /*
177              * The first time the query is advertised, don't do anything.  The
178              * component will learn nodes in the slice through the manifest
179              * received through the other subscription 
180              */
181              if (!change)
182                 return;
183              // ioi: Refubrished
184              var initial = this.initial_resources;
185              //var r_removed  = []; //
186              /*-----------------------------------------------------------------------
187                 TODO: remove this dirty hack !!!
188              */
189              resources = jQuery.map(resources, function(x){
190                 if(!('timeslot' in x)){x.timeslot=0;}
191                 return x;
192              });
193              /*
194                 TODO: handle generic keys instead of specific stuff
195                       ex: urn
196                           urn-lease
197              */
198              var initial_urn = $.map(initial, function(x){return x.urn;});
199              var resources_urn = $.map(resources, function(x){return x.urn;});
200              var r_removed = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) == -1 });
201              var r_attached = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) > -1 });
202              var r_added = $.grep(resources, function (x) { return $.inArray(x.urn, initial_urn) == -1 });
203              exists = false; // ioi
204              /*-----------------------------------------------------------------------*/
205
206              my_oTable.fnClearTable();
207              /*
208                 TODO: factorization of this code !!!
209              */
210              $.each(r_added, function(i, r) { 
211                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
212                 var type = 'add';  
213                 // Create the resource objects
214                 // ioi: refubrished
215                 var urn = r.urn;
216                 time = r.timeslot;
217                               
218                 var SPAN = "<span class='ui-icon ui-icon-close ResourceSelectedClose' id='"+urn+"'/>";
219                 var slot = "<span id='resource_"+urn+"'>" + time + "</span>"; //ioi
220                 // ioi
221                 var newline=Array();
222                 newline.push(type, urn, slot, SPAN); // ioi
223                 var line = my_oTable.fnAddData(newline);
224                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
225                 nTr.className = type;
226              });
227              $.each(r_attached, function(i, r) {  
228                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
229                 var type = 'attached';
230                 // Create the resource objects
231                 // ioi: refubrished
232                 var node = r.urn;
233                 time = r.timeslot;
234
235                 var SPAN = "<span class='ui-icon ui-icon-close ResourceSelectedClose' id='"+node+"'/>";
236                 var slot = "<span id='resource_"+node+"'>" + time + "</span>"; //ioi
237                 // ioi
238                 var newline=Array();
239                 newline.push(type, node, slot, SPAN); // ioi
240                 var line = my_oTable.fnAddData(newline);
241                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
242                 nTr.className = type;
243              });
244              $.each(r_removed, function(i, r) { 
245                 // The list contains objects
246                 // ioi: refubrished
247                 var node = r.urn;
248                 var time = r.timeslot;
249                     
250                 var SPAN = "<span class='ui-icon ui-icon-close ResourceSelectedClose' id='"+node+"'/>";
251                 var slot = "<span id='resource_"+node+"'>" + time + "</span>";
252                 // ioi
253                 var newline=Array();
254                 newline.push('remove', node, slot, SPAN); // ioi
255                 var line = my_oTable.fnAddData(newline);
256                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
257                 nTr.className = 'remove';
258              });
259
260              this.current_resources = $.merge(r_attached,r_added);
261
262              /* Allow the user to update the slice */
263              //jQuery('#updateslice-' + data.ResourceSelected.plugin_uuid).prop('disabled', false);
264
265         } // update_resources
266
267         this.record_handler = function(e, event_type, record)
268         {
269             // elements in set
270             switch(event_type) {
271                 case NEW_RECORD:
272                     /* NOTE in fact we are doing a join here */
273                     if (object.received_all)
274                         // update checkbox for record
275                         object.set_checkbox(record);
276                     else
277                         // store for later update of checkboxes
278                         object.in_set_buffer.push(record);
279                     break;
280                 case CLEAR_RECORDS:
281                     // nothing to do here
282                     break;
283                 case IN_PROGRESS:
284                     manifold.spin($(this));
285                     break;
286                 case DONE:
287                     if (object.received_all)
288                         manifold.spin($(this), false);
289                     object.received_set = true;
290                     break;
291             }
292         };
293
294         this.record_handler_all = function(e, event_type, record)
295         {
296             // all elements
297             switch(event_type) {
298                 case NEW_RECORD:
299                     // Add the record to the table
300                     object.new_record(record);
301                     break;
302                 case CLEAR_RECORDS:
303                     object.table.fnClearTable();
304                     break;
305                 case IN_PROGRESS:
306                     manifold.spin($(this));
307                     break;
308                 case DONE:
309                     if (object.received_set) {
310                         /* XXX needed ? XXX We uncheck all checkboxes ... */
311                         $("[id^='datatables-checkbox-" + object.options.plugin_uuid +"']").attr('checked', false);
312
313                         /* ... and check the ones specified in the resource list */
314                         $.each(object.in_set_buffer, function(i, record) {
315                             object.set_checkbox(record);
316                         });
317
318                         manifold.spin($(this), false);
319                     }
320                     object.received_all = true;
321                     break;
322             }
323         };
324
325         this.query_handler = function(e, event_type, data)
326         {
327             // This replaces the complex set_query function
328             // The plugin does not need to remember the query anymore
329             switch(event_type) {
330                 // Filters
331                 case FILTER_ADDED:
332                 case FILTER_REMOVED:
333                 case CLEAR_FILTERS:
334                     // XXX Here we might need to maintain the list of filters !
335                     /* Process updates in filters / current_query must be updated before this call for filtering ! */
336                     object.table.fnDraw();
337                     break;
338
339                 // Fields
340                 /* Hide/unhide columns to match added/removed fields */
341                 case FIELD_ADDED:
342                     var field = data;
343                     var oSettings = object.table.fnSettings();
344                     var cols = oSettings.aoColumns;
345                     var index = object.getColIndex(field,cols);
346                     if(index != -1)
347                         object.table.fnSetColumnVis(index, true);
348                     break;
349                 case FIELD_REMOVED:
350                     var field = data;
351                     var oSettings = object.table.fnSettings();
352                     var cols = oSettings.aoColumns;
353                     var index = object.getColIndex(field,cols);
354                     if(index != -1)
355                         object.table.fnSetColumnVis(index, false);
356                     break;
357                 case CLEAR_FIELDS:
358                     alert('Hazelnut::clear_fields() not implemented');
359                     break;
360             } // switch
361         }
362
363     } // ResourcesSelected
364
365
366     /***************************************************************************
367      * Private methods
368      ***************************************************************************/
369
370     /* Callbacks */    
371     function close_click(event){
372         //jQuery.publish('selected', 'add/'+key_value);
373         // this.parentNode is <td> this.parentNode.parentNode is <tr> 
374         // this.parentNode.parentNode.firstChild is the first cell <td> of this line <tr>
375         // this.parentNode.parentNode.firstChild.firstChild is the text in that cell
376         //var firstCellVal=this.parentNode.parentNode.firstChild.firstChild.data;
377         var remove_urn = this.id; 
378         var current_resources = event.data.instance.current_resources;
379         var list_resources = $.grep(current_resources, function(x) {return x.urn != remove_urn});
380         //jQuery.publish('selected', 'cancel/'+this.id+'/'+get_value(firstCellVal));
381         $.publish('/update-set/' + event.data.instance.options.resource_query_uuid, [list_resources, true]);
382     }
383
384 })(jQuery);