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