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

#import "ServiceFinder.h"
#import "Service.h"
#import "LocationFinder.h"
#import "Constants.h"
#import "LostRequest.h"
#import "ListServicesRequest.h"
#import "ListServicesParser.h"
#import "LostLocation.h"

@implementation ServiceFinder
@synthesize delegate, currentLocation;

- (id)init {
	if (self = [super init]) {
		lostClient = [[LostClient lostClientWithServerURL:LOST_CLIENT_SERVER_URL] retain];
		lostClient.delegate = self;
		self.currentLocation = @"------------";
	}
	return self;
}

- (void)findServices {
	[LocationFinder sharedInstance].primaryDelegate = self;
	[[LocationFinder sharedInstance] findCurrentLocation];	
}

- (void)locationUpdate:(LostLocation *) location {
	
	NSString *latitude, *longitude;
	if(location.resultLocation.coordinate.latitude < 0) {
		latitude = [NSString  stringWithFormat:@"%.2fS",-1*location.resultLocation.coordinate.latitude];
	}
	else {latitude = [NSString  stringWithFormat:@"%.2fN",location.resultLocation.coordinate.latitude];}
	
	if(location.resultLocation.coordinate.longitude < 0) {
		longitude = [NSString  stringWithFormat:@"%.2fW",-1*location.resultLocation.coordinate.longitude];
	}
	else {longitude = [NSString  stringWithFormat:@"%.2fE",location.resultLocation.coordinate.longitude];}
	
	self.currentLocation = [NSString  stringWithFormat:@"%@  %@", latitude, longitude];
	[LocationFinder sharedInstance].primaryDelegate = nil;
	ListServicesRequest *request = [ListServicesRequest requestWithLocation:location.resultLocation];
	[lostClient sendRequest:request];
}

- (void)locationUpdateError:(NSError *)error{
	self.currentLocation = @"------------";
	[LocationFinder sharedInstance].primaryDelegate = nil;
	[delegate serviceUpdateError:error];
}

- (void)lostResponse:(NSData *)response {
	ListServicesParser *parser = [ListServicesParser parserWithData:response];
	parser.delegate = self;
	[parser parseData];
}

- (void)lostResponseError:(NSError *)error {	
	[delegate serviceUpdateError:error];
}

- (void)parserResults:(NSMutableArray *)results {
	 [delegate serviceUpdate:results];
}

- (void)parserError:(NSError *)error {
	[delegate serviceUpdateError:error];
}

- (void)dealloc {
	[lostClient release];
	[currentLocation release];
	[super dealloc];
}

@end