// $Id: rrdgraph-proxy.js 1334 2010-03-14 11:14:54Z sdalu $

//
// Copyright (c)  Stephane D'Alu  2008-2010
// http://www.sdalu.com/
//


/* Class FetchDescriptionProxy
 *  (retrieve all the necessary information from a short desc)
 * !! Must be updated to override doRequest instead of load
 */
FetchDescriptionProxy = function(config){
    FetchDescriptionProxy.superclass.constructor.call(this, config);
    this.pending  = {};
    this.fetched  = {};
    this.aborted  = {};
    this.id       = 0;
    this.setApi('read', 'dummy.php');
};


Ext.extend(FetchDescriptionProxy, Ext.data.DataProxy, {
    doRequest : function(action, rs, params, reader, callback, scope, arg) {
        if (action != Ext.data.Api.actions.read)
	    return;
	
        params   = params || {};
	minidata = arg.minidata;

	// Shortcut
	var me = this;
	var id = me.id;

	// Kill previous
	if ((me.aborted[id] === false) && (me.pending[id])) {
	    me.aborted[id] = true;
	    for (var p in me.pending[id])
		Ext.Ajax.abort(p);
	}

	// Start new
	id             = me.id += 1;
	me.pending[id] = {};
	me.fetched[id] = {};
	me.aborted[id] = false;

	// Cleanup function
	var end_cleanup = function() {
	    for (var p in me.pending[id])
		return false;
	    
	    if (me.aborted[id] === false) {
		var data = [];
		Ext.each(minidata, function(grp,idx) {
		    data[idx] = { title: grp.title, id: idx, items: [] };
		    Ext.each(grp.items, function(url,pos) {
			data[idx].items[pos] = 
			    Ext.apply(me.fetched[id][url],
				      { url: url, id: idx+'-'+pos }); });
		    
		  });

		var result = null;
		var ok     = false;
		try {
		    result = reader.readRecords(data);
		    ok     = true;
		} catch(e) {
		    me.fireEvent('loadexception', me, arg, null, e);
		    callback.call(scope, null, arg, false);
		}
		if (ok)
		    callback.call(scope, result, arg, true);
	    }
	    
	    delete me.pending[id];
	    delete me.fetched[id];
	    delete me.aborted[id];

	    return true;
	};

        // Query url for description
        Ext.each(minidata, function(grp) {
  	    Ext.each(grp.items, function(url) {
	        me.fetched[id][url] = { failed: true };
	        me.pending[id][url] = Ext.Ajax.request({
		url            : url,
		params         : params,
		disableCaching : false,
	        timeout        : 5000,
	        failure        : function(response, options) {
		    delete me.pending[id][url];
		    end_cleanup();
                  },
	        success        : function(response, options) {
		    var r = Ext.decode(response.responseText);
		    if (r.success)
			me.fetched[id][url] = Ext.applyIf(Ext.apply(r.desc, 
			{ failed: false }), { labels: [] });
		    delete me.pending[id][url];
		    end_cleanup();
		  }
		}); }); });
    }
  });
