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

#import "ServicesViewController.h"
#import "OptionsViewController.h"
#import "ResultsViewController.h"
#import "LocationInputViewController.h"
#import "Service.h"
#import "Constants.h"
#import "LostLocation.h"

BOOL useKm = FALSE;
BOOL optionsUpdated = FALSE;

@implementation ServicesViewController
@synthesize servicesView, optionButton, tableView, activityIndicator, locationButton;

- (void)viewDidLoad {
    [super viewDidLoad];
	firstLoad = TRUE;
	firstCache = TRUE;
	isShowingOptions = FALSE;
	searchRadius = 1.609344;
	maxResults = 15;
	directedSearchEnabled = FALSE;
	maxResultsEnabled = FALSE;
	searchRadiusEnabled = TRUE;
	serviceFinder = [[ServiceFinder alloc]init];
	serviceFinder.delegate = self;
	cacheUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:120.0
															 target:self selector:@selector(updateResultCache:)
														   userInfo:nil repeats:YES];
	locationButton.title = serviceFinder.currentLocation;
}

- (void)didReceiveMemoryWarning {
  NSLog(@"MEMORY WARNING");  
  //[super didReceiveMemoryWarning];
}

-(void)setView:(UIView*)view
{
  if(view != nil)
  {
    [super setView:view]; 
  }
}

- (void)viewWillAppear:(BOOL)animated {
	NSIndexPath *selectedRowIndexPath = [tableView indexPathForSelectedRow];
	
	if (selectedRowIndexPath != nil) {
		[tableView deselectRowAtIndexPath:selectedRowIndexPath animated:NO];
	}
	

	if(firstLoad || [[LocationFinder sharedInstance] distanceMoved] > 500){
		firstLoad = FALSE;		
		tableView.hidden = YES;
		
		[activityIndicator startAnimating];
		optionButton.enabled = FALSE;
    locationButton.enabled = FALSE;
		[serviceFinder findServices];
	}
  
  if(locationInputViewController != nil && locationInputViewController.locationUpdated == TRUE) {
    locationInputViewController.locationUpdated = FALSE;
    [self refreshButtonPressed:self];
  }
}

- (void)loadOptionViewController {
	OptionsViewController *viewController = [[OptionsViewController alloc] initWithNibName:@"OptionsView" bundle:nil];
	optionsViewController = [viewController retain];
	optionsViewController.searchRadius = searchRadius;
	optionsViewController.searchRadiusEnabled = searchRadiusEnabled;
	optionsViewController.maxResults = maxResults;
	optionsViewController.maxResultsEnabled = maxResultsEnabled;
	optionsViewController.directedSearchEnabled = directedSearchEnabled;
	[viewController release];
}

- (void)loadResultsViewController {
	ResultsViewController *viewController = [[ResultsViewController alloc] initWithNibName:@"ResultsView" bundle:nil];
	resultsViewController = [viewController retain];
	[viewController release];
}

- (void)loadLocationInputViewController {
	LocationInputViewController *viewController = [[LocationInputViewController alloc] initWithNibName:@"LocationInputView" bundle:nil];
	//viewController.modalViewController = self;
  locationInputViewController = [viewController retain];
	[viewController release];
}

- (IBAction)refreshButtonPressed:(id)sender {
	if(isShowingOptions){
		[self optionsButtonPressed:self];
	}
	[activityIndicator startAnimating];
	optionButton.enabled = FALSE;
  locationButton.enabled = FALSE;
	tableView.hidden = YES;
	[serviceFinder findServices];
}

- (IBAction)optionsButtonPressed:(id)sender {
	if (optionsViewController == nil) {
		[self loadOptionViewController];
	}

	UIView *optionsView = optionsViewController.view;
	
	if(isShowingOptions){
    locationButton.enabled = TRUE;
		maxResults = optionsViewController.maxResults;
		searchRadius = optionsViewController.searchRadius;
		maxResultsEnabled = optionsViewController.maxResultsEnabled;
		searchRadiusEnabled = optionsViewController.searchRadiusEnabled;
		directedSearchEnabled = optionsViewController.directedSearchEnabled;
		//
		isShowingOptions = FALSE;
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:.75];
		[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.servicesView cache:YES];
		
		[optionsViewController viewWillDisappear:YES];
		[optionsView removeFromSuperview];
		[optionsViewController viewDidDisappear:YES];
		
	}
	
	else {
    locationButton.enabled = FALSE;
		optionsViewController.searchRadius = searchRadius;
		optionsViewController.maxResults = maxResults;
		optionsViewController.maxResultsEnabled = maxResultsEnabled;
		optionsViewController.searchRadiusEnabled = searchRadiusEnabled;
		optionsViewController.directedSearchEnabled = directedSearchEnabled;
		isShowingOptions = TRUE;
		
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:.75];
		[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.servicesView cache:YES];
		
		[optionsViewController viewWillAppear:YES];
		[self.servicesView addSubview:optionsView];
		[optionsViewController viewDidAppear:YES];	
	}
		
	[UIView commitAnimations];
	
	/*if(isShowingOptions) {
		optionButton.title = @"done";
	}
	else {
		optionButton.title = @"options";
	}*/
	
}

- (IBAction)locationButtonPressed:(id)sender {
  if (locationInputViewController == nil) {
		[self loadLocationInputViewController];
	}
  [self presentModalViewController:locationInputViewController animated:YES];
}


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

- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *cellIdentifier = @"ServiceCell";
    UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
	if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
	
	cell.text = [[serviceList objectAtIndex:indexPath.row] name];
	return cell;
}

- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  
  
  
  
	//if (resultsViewController == nil) {
		[self loadResultsViewController];
	//}
	
	resultsViewController.service = [serviceList objectAtIndex:indexPath.row];
	resultsViewController.searchRadius = searchRadius;
	resultsViewController.maxResults = maxResults;
	resultsViewController.maxResultsEnabled = maxResultsEnabled;
	resultsViewController.searchRadiusEnabled = searchRadiusEnabled;
	resultsViewController.directedSearchEnabled = directedSearchEnabled;
	[self.navigationController pushViewController:resultsViewController animated:YES];
}

- (void)serviceUpdate:(NSMutableArray *) services {
	locationButton.title = serviceFinder.currentLocation;
	serviceList = [services retain];
	
	if(firstCache) {
		//firstCache = FALSE;
		[cacheUpdateTimer fire];	
	}
	
	[tableView reloadData];
	[activityIndicator stopAnimating];
	optionButton.enabled = TRUE;
  locationButton.enabled = TRUE;
	tableView.hidden = NO;
}

- (void)serviceUpdateError:(NSError *)error {
	locationButton.title = serviceFinder.currentLocation;
	NSMutableArray *services = [NSMutableArray array];
	
	Service *service = [Service serviceWithName:@"Business" urn:@"urn:service:business"];
	[services addObject:service];
	
	service = [[Service alloc] initWithName:@"Communication" urn:@"urn:service:communication"];
	[services addObject:service];
	
	service = [[Service alloc] initWithName:@"Cultural" urn:@"urn:service:cultural"];
	[services addObject:service];
	
	service = [[Service alloc] initWithName:@"Financial" urn:@"urn:service:financial"];
	[services addObject:service];
	
	service = [[Service alloc] initWithName:@"Food" urn:@"urn:service:food"];
	[services addObject:service];
	
	service = [[Service alloc] initWithName:@"Lodging" urn:@"urn:service:lodging"];
	[services addObject:service];
	
	service = [[Service alloc] initWithName:@"Transportation" urn:@"urn:service:transportation"];
	[services addObject:service];
	
	serviceList = [services retain];
	
	if(firstCache) {
		//firstCache = FALSE;
		[cacheUpdateTimer fire];	
	}
	
	[tableView reloadData];
	[activityIndicator stopAnimating];
	optionButton.enabled = TRUE;
  locationButton.enabled = TRUE;
	tableView.hidden = NO;
	
	/*UIAlertView *updateErrorAlertView;
	
	updateErrorAlertView = [[UIAlertView alloc] initWithTitle:@"" 
													  message:@"Unable to locate services.\nUsing default list" 
													 delegate:self
											cancelButtonTitle:@"OK"
											otherButtonTitles:nil];
	[updateErrorAlertView show];
	[updateErrorAlertView release];*/
}

- (void)updateResultCache:(NSTimer*)theTimer {
	[LocationFinder sharedInstance].secondaryDelegate = self;
	[[LocationFinder sharedInstance] findCurrentLocation];	
}

- (void)locationUpdate:(LostLocation *) location {
	[LocationFinder sharedInstance].secondaryDelegate = nil;
	 if((firstCache || [[LocationFinder sharedInstance] distanceMoved] > 100) && ![LocationFinder sharedInstance].usingManualLocation){
		 for(int i = 0; i < serviceList.count; i++) {
			 Service *svc = [serviceList objectAtIndex:i];
			 [svc cacheResults:location.resultLocation wait:5*i];
		 }
	 }
	firstCache = FALSE;	
}

- (void)locationUpdateError:(NSError *)error {
}

- (void)dealloc {
	[servicesView release];
	[optionButton release];
	[tableView release];
	[activityIndicator release];
	[optionsViewController release];
	[resultsViewController release];
	[serviceList release];
	[serviceFinder release];
    [super dealloc];
}

@end
