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

#import "Geocoder.h"
#import "Constants.h"


@implementation Geocoder
@synthesize delegate;

- (id)init{
	if (self = [super init]) {
		receivedValidResults = FALSE;
		receivedValidResponse = FALSE;
    currentElement = 0;
		lat = [[NSMutableString string] retain];
		lng = [[NSMutableString string] retain];
    latitude = 0;
    longitude = 0;
		doneParsing = FALSE;
  }
	return self;	
}

- (void)findLocationForStreet:(NSString *) street city:(NSString *) city state:(NSString *) state zip:(NSString *) zip {
  
  receivedValidResults = FALSE;
	receivedValidResponse = FALSE;
  currentElement = 0;
	[lat setString:@""];
	[lng setString:@""];
  latitude = 0;
  longitude = 0;
	doneParsing = FALSE;
	
	NSString *xmlData = @"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><Geocode Version=\"1\"> <Address><AdminArea1>US</AdminArea1><AdminArea3>STATE</AdminArea3><AdminArea5>CITY</AdminArea5><PostalCode>ZIP</PostalCode><Street>STREET</Street></Address><AutoGeocodeCovSwitch><Name>mqgauto</Name><MaxMatches>1</MaxMatches></AutoGeocodeCovSwitch><Authentication Version=\"2\"><Password>xJ2sA3fR</Password><ClientId>81552</ClientId></Authentication></Geocode>";
	
  
	xmlData = [xmlData stringByReplacingOccurrencesOfString:@"STREET" withString:street];
  xmlData = [xmlData stringByReplacingOccurrencesOfString:@"CITY" withString:city];
  xmlData = [xmlData stringByReplacingOccurrencesOfString:@"STATE" withString:state];
  xmlData = [xmlData stringByReplacingOccurrencesOfString:@"ZIP" withString:zip];
	

  NSData *postData = [xmlData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
  NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  
	
	NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
	[theRequest setURL:[NSURL URLWithString:@"http://geocode.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 geocodeError: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 geocodeError: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:@"GeocodeResponse"]) {
		receivedValidResponse = TRUE;
  }
	
  else if ([elementName isEqualToString:@"AdminArea3"]) {
    if(receivedValidResponse) { 
      receivedValidResults = TRUE;
    }
	}
	
	else if ([elementName isEqualToString:@"Lat"]) {
		if (receivedValidResults){
			currentElement = 1;
		}
	}
  
  else if ([elementName isEqualToString:@"Lng"]) {
		if (receivedValidResults){
			currentElement = 2;
		}
	}
	else {
		currentElement = 0;	
	}
}

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

- (void)parser:(NSXMLParser *)theParser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	
	if ([elementName isEqualToString:@"GeocodeResponse"]) {
		if(latitude !=0 && longitude !=0)
		{
			doneParsing = TRUE;
      CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
			[delegate geocodeResponse:location];
      [location autorelease];
		}
		else
		{
			doneParsing = TRUE;
			[delegate geocodeError:nil];
		}
	}
	
	
	else if ([elementName isEqualToString:@"Lat"]) {
		latitude = [lat doubleValue];
    
	}
  
  else if ([elementName isEqualToString:@"Lng"]) {
		longitude = [lng doubleValue];
	}
  
	else{}
}

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

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

@end
