//
//  LocationRouter.m
//  LostClient
//
//  Created by Webster Ross III on 5/10/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "LocationRouter.h"
#import "Constants.h"


@implementation LocationRouter
@synthesize url, delegate, startLocation, endLocation;

- (id)initWithURL:(NSString * )theURL begin:(CLLocation*)theStartLocation end:(CLLocation*)theEndLocation {
	if (self = [super init]) {
		self.url = theURL;
		self.startLocation = theStartLocation;
		self.endLocation = theEndLocation;
		receivedValidResults = FALSE;
		receivedValidResponse = FALSE;
		resultCode = [[NSMutableString string] retain];
		distance = [[NSMutableString string] retain];
		totalDistance = 0;
		doneParsing = FALSE;
	}
	return self;	
}

+ (id)locationRouterWithServerURL:(NSString *)theURL begin:(CLLocation*)theStartLocation end:(CLLocation*)theEndLocation{
	return [[[LocationRouter alloc] initWithURL:theURL begin:theStartLocation end:theEndLocation] autorelease];
}

- (void)getRouteDistance{
	
	receivedValidResults = FALSE;
	receivedValidResponse = FALSE;
  currentElement = 0;
	[resultCode setString:@""];
	[distance setString:@""];
	totalDistance = 0;
	doneParsing = FALSE;
	
	NSString *xmlData = @"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><DoRoute Version=\"2\"><LocationCollection Count=\"2\"><GeoAddress><LatLng><Lat>STARTLAT</Lat><Lng>STARTLONG</Lng></LatLng></GeoAddress><GeoAddress><LatLng><Lat>ENDLAT</Lat><Lng>ENDLONG</Lng></LatLng></GeoAddress></LocationCollection><RouteOptions Version=\"2\"><RouteType>1</RouteType><NarrativeType>-1</NarrativeType><MaxShape>0</MaxShape></RouteOptions><Authentication Version=\"2\"><Password>xJ2sA3fR</Password><ClientId>81552</ClientId></Authentication></DoRoute>";
	
	
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"STARTLAT" withString:[NSString stringWithFormat:@"%f",startLocation.coordinate.latitude]];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"STARTLONG" withString:[NSString stringWithFormat:@"%f",startLocation.coordinate.longitude]];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"ENDLAT" withString:[NSString stringWithFormat:@"%f",endLocation.coordinate.latitude]];
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"ENDLONG" withString:[NSString stringWithFormat:@"%f",endLocation.coordinate.longitude]];
	
	
	//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:@"http://route.dev.mapquest.com:80/mq/mqserver.dll?e=5&"]];
	[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) {
		[delegate routerError: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 {
	[delegate routerError:nil];
	[receivedData release];
	[connection release];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
	
	//NSString *tmp = [[NSString alloc]initWithData:receivedData encoding:1];
	//NSLog(tmp);
	
	[receivedData autorelease];
	[connection release];
	
	NSXMLParser *parser = [[NSXMLParser alloc] initWithData:receivedData];
	[parser setDelegate:self];
	[parser setShouldResolveExternalEntities:YES];
	[parser parse];
}

- (void)parser:(NSXMLParser *)theParser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
	
	
	if ([elementName isEqualToString:@"DoRouteResponse"]) {
		receivedValidResponse = TRUE;
    }
	
    else if ([elementName isEqualToString:@"ResultCode"]) {
		if (receivedValidResponse){
			currentElement = 1;
		}
	}
	
	else if ([elementName isEqualToString:@"Distance"]) {
		if (receivedValidResults){
			currentElement = 2;
		}
	}
	else {
		currentElement = 0;	
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (currentElement == 1) {
		[resultCode appendString:string];
		return;
	}
	
	if(currentElement == 2){
		[distance appendString:string];
		return;
	}
}

- (void)parser:(NSXMLParser *)theParser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	
	if ([elementName isEqualToString:@"DoRouteResponse"]) {
		if(totalDistance > 0)
		{
			doneParsing = TRUE;
			[delegate routerResponse:totalDistance];
		}
		else
		{
			doneParsing = TRUE;
			[delegate routerError:nil];
		}
	}
	
	else if ([elementName isEqualToString:@"ResultCode"]) {
		if([resultCode isEqualToString:@"0"])
		{
			receivedValidResults = TRUE;
		}
	}
	
	else if ([elementName isEqualToString:@"Distance"]) {
		totalDistance += [distance doubleValue];
		[distance setString:@""];
	}
	else{}
}


- (void)parser:(NSXMLParser *)theParser parseErrorOccurred:(NSError *)parseError {
	doneParsing = TRUE;
	[delegate routerError:nil];
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {
	if(!doneParsing) {[delegate routerError:nil];}
}

@end
