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