/*
 * ServerConnector.j
 * RouteIntelligence
 *
 * Created by P. Miranda on June 23, 2010.
 * Copyright 2010, Route Miner S.A. All rights reserved.
 */



@import <Foundation/CPObject.j>
@import "RMURLConnection.j"
@import "ServerAnswer.j"
@import "ServerAnswerXML.j"



@implementation ServerConnector : CPObject {
    id ipAddr;
    id queu;
    id asynCoun;
	id data;
}



- (id) init {
   [super init];
   ipAddr = @"http://199.102.237.34/cgi-bin/rmws";
   asynCoun = 0;
   data = 0;
   return self;
}



- (id) initWithURL:(CPString)urlAddressNew {
   [self init];
   ipAddr = urlAddressNew;
	queu = [[CPOperationQueue alloc] init];
   return self;
}



- (ServerAnswerXML) obtainFromServerXML:(CPString)requ  {
	var resp = nil;
	var srvrResp = nil;
	var striURL = [CPString stringWithFormat:@"%@?%@",ipAddr,requ];
	var uurl = [CPURL URLWithString:striURL];
	if ( uurl ) {
		var rurl= [CPURLRequest requestWithURL:uurl];
		var urlr;
		resp= [RMURLConnection sendSynchronousRequest:rurl returningResponse:urlr];
	}
	if ( resp ) {
//                var _ans = [CPData dataWithRawString:resp];
//                console.log(_ans);
//              console.log(resp);
		srvrResp = [[ServerAnswerXML alloc] initWithAnswer:resp];
        }
	return srvrResp;
}    



- (int) obtainAsynchronouslyFromServerXML:(CPString)_request completionHandler:(Function)hand  {
	var striURL = [CPString stringWithFormat:@"%@?%@",ipAddr,_request];
	var uurl= [CPURL URLWithString:striURL];
	if ( uurl ) {
		var rurl= [CPURLRequest requestWithURL:uurl];
		var urlr;
		[RMURLConnection sendAsynchronousRequest:rurl queue:queu completionHandler:hand];
		return 0;
	}
	return 1;
}    



@end
