/**
* SABS Agent Search And Booking Software
* <http://www.sabsagent.com>
* Copyright(c) 2001-2009, Micros Travel
*
* @author Jacek Spera <jspera@micros.com>
*/

/**
* Abstract class defining methods for different
* types of workers
*/
BaseWorker = function(cfg){
    this.addEvents('start','error','complete');
    Ext.apply(this,cfg);
    BaseWorker.superclass.constructor.call(this);
};
Ext.extend(BaseWorker, Ext.util.Observable, {
    searchType: null,
    session: null,
	 extraParams: null,
    lastResponse: null, // crude response
    start: function(){
        var type = this.searchType;
        var conn = this.getConnection();
        var params = this.getParams(type);
        this.fireEvent('start', this);
        conn.request({
            params: params,
            callback: this.getResponseHandler(type),
            scope: this
        });
    },
    getConnection: function(type){
        if(!this.connection){
            this.connection = ExtFactory.get('Connection',
                { url: this.url } );
        }
        return this.connection;
    },
    getResponseHandler: function(){
        return this.onResponse;
    },
    onResponse: function(options, success, response){
        if(success) {
            // store this 
            this.lastResponse = response.responseText;
            try {
                response = ExtFactory.getExt().decode(
                    response.responseText);
            } catch (e) {
                this.fireEvent('error', this, this.searchType, "CLIENT: Malformed json");
                return;
            }
            // make sure its array
            if(!Ext.isArray(response)){
                response = [response];
            }
				if (!response[0])
				{
					console.log('empty response');
					return;
				}

            if(response[0].RecType == 'ERR'){
                this.onErrorInHeader(response);
            }
            else if(response[0].RecType == 'SYS'){
                this.onOkInHeader(response);
            }
            else {
                this.fireEvent('error', this, this.searchType, "CLIENT: Unknown message");
            }
        } else {
            var stat = response.status;
            this.fireEvent('error', this, this.searchType,
                'HTTP '+stat+': '+response.statusText, true);
        }
    },
    onErrorInHeader: function(response){
        this.fireEvent('error', this, this.searchType,
            response[0].ErrorText);
    },
    onOkInHeader: Ext.emptyFn,
    getParams: Ext.emptyFn,
    getApiType: function(type){
        var apiType = this.SABSConfig.productToApiType[type];
        if(apiType){
            return apiType;
        }
        throw 'product '+type+' has not got apiType assigned';
    }
});
