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

#import "ResultsViewController.h"
#import "Constants.h"
#import "Result.h"
#import "ResultDetailViewController.h"

@implementation ResultsViewController
@synthesize tableView, activityIndicator, searchRadius, maxResults, directedSearchEnabled, maxResultsEnabled,
searchRadiusEnabled, service;

- (void)viewDidLoad {
    [super viewDidLoad];
	resultsFinder = [[ResultsFinder alloc]init];
	resultsFinder.delegate = self;
	detailsDisplayed = FALSE;
	usingCache = FALSE;
}

- (void)loadResultDetailViewController {
	ResultDetailViewController *viewController = [[ResultDetailViewController alloc] initWithNibName:@"ResultDetailView" bundle:nil];
	resultDetailViewController = [viewController retain];
	[viewController release];
}

- (void)viewWillDisappear:(BOOL)animated {
	resultsFinder.delegate = nil;
}

- (void)viewWillAppear:(BOOL)animated {
	
	self.title = service.name;
	self.tableView.rowHeight = 80;
  
  
	if([self.tableView numberOfRowsInSection:0] > 0 && !detailsDisplayed) {
		[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
	}
	
	NSIndexPath *selectedRowIndexPath = [tableView indexPathForSelectedRow];
	if (selectedRowIndexPath != nil) {
        [tableView deselectRowAtIndexPath:selectedRowIndexPath animated:NO];
    }
	
	if(!detailsDisplayed){
		resultsFinder.serviceURN = service.urn;
		resultsFinder.service = service;
		if(maxResultsEnabled) {
			resultsFinder.maxResults = maxResults;		
		}
		else {
			resultsFinder.maxResults = LOST_VALUE_UNLIMITED;	
		}
		
		if(searchRadiusEnabled) {
			resultsFinder.searchRadius = searchRadius;	
		}
		else {
			resultsFinder.searchRadius = LOST_VALUE_UNLIMITED;	
		}
		
		
		resultsFinder.isDirectedSearch = directedSearchEnabled;
		
		
		tableView.hidden = YES;
		[activityIndicator startAnimating];
		//resultsFinder.delegate = self;
		[resultsFinder findResults];
		//disbable button here
	}
	
	else {
		detailsDisplayed = FALSE;	
	}
}

- (void)resultsUpdate:(NSMutableArray *) results {
	resultsList = [results retain];
	service.results = results;
	[tableView reloadData];
	[activityIndicator stopAnimating];
	tableView.hidden = NO;
}

- (void)resultsUpdateError:(NSError *)error {
	resultsList = nil;
	service.results = nil;
	[tableView reloadData];
	[activityIndicator stopAnimating];
	tableView.hidden = NO;
	UIAlertView *updateErrorAlertView;
	
	if(service.cachedResults.length > 0 && !usingCache && ![LocationFinder sharedInstance].usingManualLocation) {
		usingCache = TRUE;
		
		[resultsFinder parseResults:service.cachedResults];
		updateErrorAlertView = [[UIAlertView alloc] initWithTitle:@"" 
														  message:@"No results found\nDisplaying cached results" 
														 delegate:self
												cancelButtonTitle:@"OK"
												otherButtonTitles:nil];
	}
	
	else {
		updateErrorAlertView = [[UIAlertView alloc] initWithTitle:@"" 
														  message:@"No results found" 
														 delegate:self
												cancelButtonTitle:@"OK"
												otherButtonTitles:nil];
	}
	
	[updateErrorAlertView show];
	[updateErrorAlertView release];
	
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
	
	if([alertView.message isEqualToString:@"No results found"])
	{
		[self.navigationController popViewControllerAnimated:YES];	
	}
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [resultsList count];
}

- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *cellIdentifier = @"ResultCell";
    UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
	if (cell == nil) {
		cell = [self tableviewCellWithReuseIdentifier:cellIdentifier];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
	
	[self configureCell:cell forIndexPath:indexPath];
	return cell;
}

- (UITableViewCell *)tableviewCellWithReuseIdentifier:(NSString *)identifier {
	
	CGRect rect;
	rect = CGRectMake(0, 0, 320, 60);
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:rect reuseIdentifier:identifier] autorelease];
	UILabel *label;
	
	rect = CGRectMake(10, 13, 235, 30);
	label = [[UILabel alloc] initWithFrame:rect];
	label.tag = 1;
	label.font = [UIFont boldSystemFontOfSize:18];
	[cell.contentView addSubview:label];
	label.highlightedTextColor = [UIColor whiteColor];
	[label release];
	
	
	rect = CGRectMake(13, 38, 280, 30);
	label = [[UILabel alloc] initWithFrame:rect];
	label.tag = 2;
	label.font = [UIFont systemFontOfSize:14];
	label.textColor = [UIColor darkGrayColor];
	[cell.contentView addSubview:label];
	label.highlightedTextColor = [UIColor whiteColor];
	[label release];
	
	rect = CGRectMake(243, 13, 50, 30);
	label = [[UILabel alloc] initWithFrame:rect];
	label.tag = 3;
	label.font = [UIFont systemFontOfSize:14];
	label.textColor = [UIColor blueColor];
	label.textAlignment =  UITextAlignmentRight;
	[cell.contentView addSubview:label];
	label.highlightedTextColor = [UIColor whiteColor];
	[label release];
	
	return cell;
}

- (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath {
    
	Result *result = [resultsList objectAtIndex:indexPath.row];	
	
	UILabel *label;
	label = (UILabel *)[cell viewWithTag:1];
	label.text = result.name;
	
	label = (UILabel *)[cell viewWithTag:2];
	label.text = result.location;
	
	label = (UILabel *)[cell viewWithTag:3];
	if(useKm){label.text = result.distanceKM;}
	else{label.text = result.distanceMI;}
	
}    

- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if (resultDetailViewController == nil) {
		[self loadResultDetailViewController];
	}
	resultDetailViewController.result = [resultsList objectAtIndex:indexPath.row];
	detailsDisplayed = TRUE;
	[self.navigationController pushViewController:resultDetailViewController animated:YES];
}

- (void)dealloc {
	[tableView release];
	[activityIndicator release];
	[service release];
	[resultsList release];
	//[resultsFinder release];
	[resultDetailViewController release];
    [super dealloc];
}

@end
