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

#import "LocationFinder.h"
#import "Constants.h"
#import "LostRequest.h"
#import "ResultsFinder.h"
#import "FindServicesRequest.h"
#import "FindServicesParser.h"
#import "Result.h"
#import "LostLocation.h"


@implementation ResultsFinder

@synthesize delegate, serviceURN, maxResults, searchRadius, searchLocation, isDirectedSearch, service;

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

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

- (void)parseResults:(NSData *)resultData {
	//NSString *tmp = [[NSString alloc] initWithData:resultData encoding:1];
	//NSLog(tmp);
	FindServicesParser *parser = [FindServicesParser parserWithData:resultData];
	parser.searchLocation = searchLocation;
	parser.delegate = self;
	[parser parseData];

}

- (void)locationUpdate:(LostLocation *) location {	
	self.searchLocation = location.searchLocation; 
	[LocationFinder sharedInstance].primaryDelegate = nil;
	CLLocation *oldLocation = [LocationFinder sharedInstance].lastLocation;
	NSTimeInterval timeInterval = [searchLocation.timestamp timeIntervalSinceDate:oldLocation.timestamp];
	

	if(service.results && !optionsUpdated && [[LocationFinder sharedInstance] distanceMoved] <= 100 && timeInterval < 86400)
	{
		[delegate resultsUpdate:service.results];
	}
	else
	{
		service.resultsRadius = searchRadius;
		FindServicesRequest *request = [FindServicesRequest requestWithLocation:location.resultLocation service:serviceURN searchRadius:searchRadius maxResults:maxResults directed:isDirectedSearch];
		[lostClient sendRequest:request];
	}
	
	optionsUpdated = FALSE;

}

- (void)locationUpdateError:(NSError *)error{
	[LocationFinder sharedInstance].primaryDelegate = nil;
	[delegate resultsUpdateError:error];
}

- (void)lostResponse:(NSData *)response {
	//NSString *tmp = [[NSString alloc] initWithData:response encoding:1];
	//NSLog(tmp);
	[self parseResults:response];
}

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

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

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

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

@end
