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

#import "LostParser.h"
#import "FindServicesParser.h"
#import "Result.h"
#import "Constants.h"

@implementation FindServicesParser
@synthesize searchLocation;

+ (id)parserWithData:(NSData *)data {
	return [[[super alloc] initWithData:data] autorelease];	
}

- (void)parseData {
		
	[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:@"errors"]) {
		//[theParser abortParsing];
		[delegate parserError:[NSError errorWithDomain:LOST_PARSER_ERROR_DOMAIN code:0 userInfo:nil]];
    }
	
    else if ([elementName isEqualToString:@"findServiceResponse"]) {
		if (!results){
			results = [[NSMutableArray alloc] init];
		}
		[results removeAllObjects];
	}
	
	else if ([elementName isEqualToString:@"mapping"]) {
		currentResult = [[Result alloc] init];
	}
	
	else if ( [elementName isEqualToString:@"displayName"]) {
		currentElement = LOSTPARSE_ELEMENT_DISPLAYNAME;
	}
	
	else if ( [elementName isEqualToString:@"LOC"]) {
		currentElement = LOSTPARSE_ELEMENT_LOC;
	}
	
	else if ( [elementName isEqualToString:@"serviceNumber"]) {
		currentElement = LOSTPARSE_ELEMENT_NUMBER;
	}
	
	else if ( [elementName isEqualToString:@"uri"]) {
		currentElement = LOSTPARSE_ELEMENT_URI;
	}
	
	else if ( [elementName isEqualToString:@"p2:pos"]) {
		if(searchLocation){
			currentElement = LOSTPARSE_ELEMENT_POS;
		}
	}
	
	else {
		currentElement = 0;	
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (currentElement == LOSTPARSE_ELEMENT_DISPLAYNAME) {
		[currentResult.name appendString:string];
		return;
	}
	
	if(currentElement == LOSTPARSE_ELEMENT_LOC){
		[currentResult.location appendString:string];
		return;
	}
	
	if(currentElement == LOSTPARSE_ELEMENT_NUMBER){
		[currentResult.number appendString:string];
		return;
	}
	
	if(currentElement == LOSTPARSE_ELEMENT_URI){
		[currentResult.uri appendString:string];
		return;
	}
	
	if(currentElement == LOSTPARSE_ELEMENT_POS){
		[currentResult.coords appendString:string];
		return;
	}
}

- (void)parser:(NSXMLParser *)theParser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	
	if ([elementName isEqualToString:@"findServiceResponse"]) {
		if([results count] <= 0) {
			//[theParser abortParsing];
			[delegate parserError:[NSError errorWithDomain:LOST_PARSER_ERROR_DOMAIN code:0 userInfo:nil]];
		}
		else {
			[delegate parserResults:results];
		}
	}
	
	else if ([elementName isEqualToString:@"mapping"]) {
		[results addObject:currentResult];
	}
	
	else if ([elementName isEqualToString:@"p2:pos"]) {
		if(searchLocation){
			CLLocation *dst = nil;
			NSArray *locationData = [currentResult.coords componentsSeparatedByString:@" "];
			double latitude = [[locationData objectAtIndex:0] doubleValue];
			double longitude = [[locationData objectAtIndex:1] doubleValue];
		
			if(latitude == 0.0 || latitude == HUGE_VAL || longitude == 0.0 || longitude== HUGE_VAL) {
		
				currentResult.distanceKM = @"??km";
				currentResult.distanceMI = @"??mi";
			}
			else {
				dst = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
				double distance = [searchLocation getDistanceFrom:dst] / 1000;
				
				if(distance < 50.0) {
					currentResult.distanceKM = [NSString stringWithFormat:@"%.1fkm",distance];
					currentResult.distanceMI = [NSString stringWithFormat:@"%.1fmi",distance*0.621371192];
				}
				else {
					currentResult.distanceKM = @">50km";
					currentResult.distanceMI = @">30mi";
				}
			}
			
			currentResult.searchLocation = searchLocation;
			currentResult.resultLocation = dst;
			[dst release];
			
		}
	}
	else{}
}


- (void)parser:(NSXMLParser *)theParser parseErrorOccurred:(NSError *)parseError {
	[delegate parserError:[NSError errorWithDomain:LOST_PARSER_ERROR_DOMAIN code:0 userInfo:nil]];
}


- (void)dealloc {
	[results release];
	[currentResult release];
	[searchLocation release];
    [super dealloc];
}


@end