/*
 * RMURLConnection.j
 * RouteIntelligence
 *
 * Created by R. Beck on October 23, 2013.
 * Copyright 2013, Route Miner S.A. All rights reserved.
 */



@import <Foundation/CPObject.j>



@implementation RMURLConnection : CPURLConnection {
/*
CPURLRequest _originalRequest;
CPURLRequest _request;
id <CPURLConnectionDelegate> _delegate;
BOOL _isCanceled;
BOOL _isLocalFileConnection;
HTTPRequest _HTTPRequest;
CPOperationQueue _operationQueue;
CPOperation _connectionOperation;
Function _handler;
*/
 id resu ;
}



- (void)_initWithRequest:(CPURLRequest)aRequest {
	_request = aRequest;
	_originalRequest = [aRequest copy];
	_isCanceled = NO;
	var URL = [_request URL],
	scheme = [URL scheme];
	_isLocalFileConnection = scheme === "file" || ((scheme === "http" || scheme === "https") &&
	window.location && (window.location.protocol === "file:" || window.location.protocol === "app:"));
	_HTTPRequest = new CFHTTPRequest();
	_HTTPRequest.timeout = 60000;

	//_HTTPRequest.setTimeout([aRequest timeoutInterval] * 1000);
	//_HTTPRequest.setWithCredentials([aRequest withCredentials]);
}



- (id)_initWithRequest:(CPURLRequest)aRequest queue:(CPOperationQueue)aQueue completionHandler:(Function)aHandler {
	self = [super init];
	if (self) {
		_delegate = nil;
		_operationQueue = aQueue;
		_handler = aHandler;
		//_connectionOperation = [[_AsynchronousConnectionOperation alloc] initWithFunction:aHandler];
		//[_operationQueue addOperation:_connectionOperation];
		[self _initWithRequest:aRequest];
		[self start];
	}
	return self;
}


 
 - (void) _readyStateDidChange {
 	var stat = _HTTPRequest.readyState();
 	console.log("_readyStateDidChange with readyState="+stat);
 	if ( stat == CFHTTPRequest.CompleteState ) {
		var respText = _HTTPRequest.responseText();	
		//var data = [CPData dataWithRawString:respText];
		_handler(respText);
	}
	else
		console.log("_readyStateDidChange waiting...");
 }



+ (CPURLConnection) sendAsynchronousRequest:(CPURLRequest)aRequest queue:(CPOperationQueue)aQueue completionHandler:(Function)aHandler {
	return [[self alloc] _initWithRequest:aRequest queue:aQueue completionHandler:aHandler];
}


 
+ (CPData) sendSynchronousRequest:(CPURLRequest)aRequest returningResponse:(CPURLResponse)aURLResponse {
	try {
                var requ = [[aRequest URL] absoluteString];
                var aURL = [[requ componentsSeparatedByString:@"?"] objectAtIndex:0];
                var body = [[requ componentsSeparatedByString:@"?"] objectAtIndex:1];
                body = [body stringByReplacingOccurrencesOfString:@"query=" withString:@""];
                body = [body stringByReplacingOccurrencesOfString:@"user=" withString:@""];
                var quer = [[body componentsSeparatedByString:@"&"] objectAtIndex:0];
                var user = [[body componentsSeparatedByString:@"&"] objectAtIndex:1];
                var resu;

        $.ajaxSetup({async: false});
		$.post( aURL, { query: quer, user: user })
 				 .always(function( data ) {
                  resu = data;
//                  console.log("Resu es (dentro del callback) es " + resu);
                  return resu;
		});

		return resu;

		}
	catch (anException) {

	}
	return nil;
}

 
/*
 - (void) start {
	_isCanceled = NO;
	try {
		_HTTPRequest.open([_request HTTPMethod], [[_request URL] absoluteString], YES);
		_HTTPRequest.onreadystatechange = function() { [self _readyStateDidChange]; };
		var fields = [_request allHTTPHeaderFields],
		key = nil,
		keys = [fields keyEnumerator];
		while ((key = [keys nextObject]) !== nil)
			_HTTPRequest.setRequestHeader(key, [fields objectForKey:key]);
		//_HTTPRequest.timeout = 60000;
 		_HTTPRequest.send([_request HTTPBody]);
	}
	catch (anException) {
		if ( [_delegate respondsToSelector:@selector(connection:didFailWithError:)] )
			[_delegate connection:self didFailWithError:anException];
 	}
 }
*/
 
 - (void) start {
	_isCanceled = NO;
	try {
		console.log("method="+[_request HTTPMethod]+"    request="+[[_request URL] absoluteString]);
		_HTTPRequest.open([_request HTTPMethod], [[_request URL] absoluteString], YES);
		_HTTPRequest.onreadystatechange = function() { [self _readyStateDidChange]; };
		_HTTPRequest.ontimeout = function() { console.log("timedout"); [self _didTimeout]; };
		var fields = [_request allHTTPHeaderFields],
			key = nil,
			keys = [fields keyEnumerator];
		while ((key = [keys nextObject]) !== nil) {
			console.log("start "+key);
			_HTTPRequest.setRequestHeader(key, [fields objectForKey:key]);
		}
		console.log("start send :"+[_request HTTPBody]);
		_HTTPRequest.send([_request HTTPBody]);
	}
	catch (anException) {
		[self _sendDelegateDidFailWithError:anException];
	}
	console.log("started");
}
 
 
 @end
 
 
 
 
 
 /*
@implementation _AsynchronousConnectionOperation : CPOperation
{
 BOOL _didReceiveResponse;
 CPURLResponse _response;
 CPData _data;
 CPError _error;
 Function _operationFunction;
}



- (id) initWithFunction:(Function)aFunction {
	self = [super init];
	if (self) {
		_didReceiveResponse = NO;
		_response = nil;
		_data = nil;
		_error = nil;
		_operationFunction = aFunction;
	}
	return self;
}



- (void) _setResponse:(CPURLResponse)aResponse data:(CPData)aData error:(CPError)anError {
	console.log("_AsynchronousConnectionOperation::setResponse");
	_didReceiveResponse = YES;
	_response = aResponse;
	_data = aData;
	_error = anError;
}



- (void) main {
	console.log("_AsynchronousConnectionOperation::main");
	_operationFunction(_response, _data, _error);
}



- (BOOL) isReady {
	console.log("_AsynchronousConnectionOperation::isReady");
	return (_didReceiveResponse && [super isReady]);
}
@end
*/
