/*
 * LSPN
 * Copyright(c) 2008 Color Shift, Inc.
 * Created on January 22, 2008
 * By Mark Hulka
 *
 */
 
/*

    JayRock.RpcConnection
    ---------------------
    Extended Connection object for use with JayRock RPC

    Usage: 
	ds : new Ext.data.Store({
    	proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:'http://localhost/JsonRpcService.ashx', rpcMethod:'someMethod'})),
    	    baseParams: {testparam: 'test1'},
        	method: "POST", // so you don't have to set 'Idempotent' to true in your service.
            remoteSort: true,
            sortInfo : {field: "time", direction: "DESC"},
        reader: new Ext.data.JsonReader({
           root: 'result',
       },  ['column1', 'column2', 'column3', 'column4'])
    });
 
 */

Ext.namespace('JayRock');

JayRock.RpcConnection = function(config)
{
    Ext.apply(this, config);
    JayRock.RpcConnection.superclass.constructor.call(this);
}

// Extend the ExtJS Connection Object
Ext.extend(JayRock.RpcConnection, Ext.data.Connection) ;

JayRock.RpcConnection.prototype.handleResponse = function(response) 
{
	var o = eval("("+response.responseText+")");
	if (o.session_timeout)
	{
    	Ext.Msg.alert('Session Expired', 'Your session has expired. Please refresh the page to log back in.');  	
	}
	
    this.transId = false;
    var options = response.argument.options;
    response.argument = options ? options.argument : null;
    this.fireEvent("requestcomplete", this, response, options);
    Ext.callback(options.success, options.scope, [response, options]);
    Ext.callback(options.callback, options.scope, [options, true, response]);
}

JayRock.RpcConnection.prototype.getJsonAccessor = function(){
        var re = /[\[\.]/;
        return function(expr) {
            try {
                return(re.test(expr))
                    ? new Function("obj", "return obj." + expr)
                    : function(obj){
                        return obj[expr];
                    };
            } catch(e){}
            return Ext.emptyFn;
        };
    }

// All we really do is replace one part of this method
// so the request is encoded JSON instead of URL parameters
JayRock.RpcConnection.prototype.request = function(o) 
{
    if (o == undefined)
        o = this;
        
    if(this.fireEvent("beforerequest", this, o) !== false){
        var p = o.params;

        if(typeof p == "function"){
            p = p.call(o.scope||window, o);
        }
        if(typeof p == "object"){
            // START RPC CHANGE TO THIS METHOD
            var x = [];
            x = {
                params:p,
                id:0,
                method:this.rpcMethod
            };
            
            x = Ext.util.JSON.encode(x);
            p = x;
            // END RPC CHANGE
        }
        if(this.extraParams){
            var extras = Ext.urlEncode(this.extraParams);
            p = p ? (p + '&' + extras) : extras;
        }

        var url = o.url || this.url;
        if(typeof url == 'function'){
            url = url.call(o.scope||window, o);
        }

        if(o.form){
            var form = Ext.getDom(o.form);
            url = url || form.action;

            var enctype = form.getAttribute("enctype");
            if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
                return this.doFormUpload(o, p, url);
            }
            var f = Ext.lib.Ajax.serializeForm(form);
            p = p ? (p + '&' + f) : f;
        }

        var hs = o.headers;
        if(this.defaultHeaders){
            hs = Ext.apply(hs || {}, this.defaultHeaders);
            if(!o.headers){
                o.headers = hs;
            }
        }

        var cb = {
            success: this.handleResponse,
            failure: this.handleFailure,
            scope: this,
            argument: {options: o},
            timeout : this.timeout
        };

        var method = o.method||this.method||(p ? "POST" : "GET");

        if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
            url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
        }

        if(typeof o.autoAbort == 'boolean'){ // options gets top priority
            if(o.autoAbort){
                this.abort();
            }
        }else if(this.autoAbort !== false){
            this.abort();
        }
        if((method == 'GET' && p) || o.xmlData || o.jsonData){
            url += (url.indexOf('?') != -1 ? '&' : '?') + p;
            p = '';
        }
        this.transId = Ext.lib.Ajax.request(method, url, cb, p, o);
        return this.transId;
    }else{
        Ext.callback(o.callback, o.scope, [o, null, null]);
        return null;
    }
}
