//
//  LostClient.m
//  LostClient
//
//  Created by Webster Ross III on 4/2/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "LostClient.h"
#import "LostRequest.h"
#import "Constants.h"


@implementation LostClient

@synthesize lostServerURL;
@synthesize delegate;

- (id)initWithServerURL:(NSString *)theServerURL {
	if (self = [super init]) {
		self.lostServerURL = theServerURL;
	}
	return self;
}

+ (id)lostClientWithServerURL:(NSString *)theServerURL {
	return [[[LostClient alloc] initWithServerURL:theServerURL] autorelease];
}

- (void) sendRequest:(LostRequest *)theLostRequest {
	NSString *xmlData = [theLostRequest buildXML];
	//NSLog(xmlData);
    NSData *postData = [xmlData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  
	
	NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
	[theRequest setURL:[NSURL URLWithString:self.lostServerURL]];
	[theRequest setCachePolicy:LOST_CLIENT_CACHE_POLICY];
	[theRequest setTimeoutInterval:LOST_CLIENT_TIMEOUT_INTERVAL];
	
	[theRequest setHTTPMethod:@"POST"];
	[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
    [theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];  
	[theRequest setValue:@"close" forHTTPHeaderField:@"Connection"];  
    [theRequest setHTTPBody:postData]; 
	
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest 
																  delegate:self 
														  startImmediately:YES];
	
	if (connection == nil) {
		[self.delegate lostResponseError:[NSError errorWithDomain:LOST_NSURLCONN_ERROR_DOMAIN code:0 userInfo:nil]];
	}
	else {
		receivedData = [[NSMutableData data] retain];
	}
	
	[theRequest release];
}

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {	
    [receivedData setLength:0];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	[self.delegate lostResponseError:[NSError errorWithDomain:LOST_NSURLCONN_ERROR_DOMAIN code:0 userInfo:nil]];
	[receivedData release];
	[connection release];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
	[self.delegate lostResponse:receivedData];
	[receivedData autorelease];
	[connection release];
}

- (void)dealloc {
	[lostServerURL release];
	[receivedData release];
	[super dealloc];
}

@end
