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

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

@interface ResultDetailViewController (private)
-(void)getRealTimeServiceInfo;
-(void)getMQTest;
@end

@implementation ResultDetailViewController

@synthesize tableView, result, tabBar;

- (void)viewWillAppear:(BOOL)animated {
	NSIndexPath *selectedRowIndexPath = [tableView indexPathForSelectedRow];
    if (selectedRowIndexPath != nil) {
        [tableView deselectRowAtIndexPath:selectedRowIndexPath animated:NO];
	}
	
	CGRect titleRect = CGRectMake(0, 0, 300, 75);
    UILabel *tableTitle = [[UILabel alloc] initWithFrame:titleRect];
    tableTitle.textColor = [UIColor blackColor];
    tableTitle.backgroundColor = [UIColor clearColor];
    tableTitle.opaque = YES;
    tableTitle.font = [UIFont boldSystemFontOfSize:18];
    tableTitle.text = [result name];
	tableTitle.textAlignment = UITextAlignmentCenter;
	tableTitle.numberOfLines = 2;
    tableView.tableHeaderView = tableTitle;
    [tableTitle release];
	[tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section {
	if(section == 1){return 2;}
	return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView {
	if(result.uri && [result.uri length] > 0) {
		return 3;
	}
	return 2;
}

- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *cellIdentifier = @"ResultDetailCell";
    UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
	UILabel *label, *value;
	
	if([indexPath section] == 2) {
		if (cell == nil) {
			cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
			
			label = [[[UILabel alloc] initWithFrame:CGRectMake(12.0, 19.0, 70.0, 25.0)] autorelease];
			label.tag = 1;
			label.font = [UIFont systemFontOfSize:14.0];
			label.textAlignment = UITextAlignmentLeft;
			label.textColor = [UIColor blueColor];
			[cell.contentView addSubview:label];
			
			
			
			value = [[[UILabel alloc] initWithFrame:CGRectMake(85.0, 20.0, 200.0, 125)] autorelease];
			value.tag = 2;
			value.font = [UIFont systemFontOfSize:14.0];
			value.textColor = [UIColor blackColor];
			value.lineBreakMode = UILineBreakModeWordWrap;
			value.numberOfLines = 0;
			[cell.contentView addSubview:value];
		}
		else {
			label = (UILabel *)[cell.contentView viewWithTag:1];
			value = (UILabel *)[cell.contentView viewWithTag:2];
		}
		
		
		label.text = @"info:";
		value.text = @"";
	}
	
	else{
		if (cell == nil) {
			cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
			
			label = [[[UILabel alloc] initWithFrame:CGRectMake(12.0, 19.0, 70.0, 25.0)] autorelease];
			label.tag = 1;
			label.font = [UIFont systemFontOfSize:14.0];
			label.textAlignment = UITextAlignmentLeft;
			label.textColor = [UIColor blueColor];
			[cell.contentView addSubview:label];
			
			
			
			value = [[[UILabel alloc] initWithFrame:CGRectMake(85.0, 20.0, 200.0, 25)] autorelease];
			value.tag = 2;
			value.font = [UIFont systemFontOfSize:14.0];
			value.textColor = [UIColor blackColor];
			value.lineBreakMode = UILineBreakModeWordWrap;
			value.numberOfLines = 0;
			[cell.contentView addSubview:value];
		}
		else {
			label = (UILabel *)[cell.contentView viewWithTag:1];
			value = (UILabel *)[cell.contentView viewWithTag:2];
		}
		
		if([indexPath section] == 0){
			label.text = @"telephone:";
			value.text = [result number];
			//[label sizeToFit];
			//[value sizeToFit];
		}
		else {
			if([indexPath row] == 0){
				label.text = @"address:";
				value.text = [result location];
				//[label sizeToFit];
				//[value sizeToFit];
			}
			else {
				label.text = @"distance:";
				if(result.routeDistance <= 0)
				{
					value.text = @"";
					LocationRouter *router = [LocationRouter locationRouterWithServerURL:@"" begin:result.searchLocation end:result.resultLocation];
					router.delegate = self;
					[router getRouteDistance];
				}
				else{
					if(!useKm){value.text = [NSString stringWithFormat:@"%.1f mi",result.routeDistance];}
					else{value.text = [NSString stringWithFormat:@"%.1f km",result.routeDistance*1.609344];}
				
				}
			}
		}
		
	}
	
	if([indexPath section] == 2) {
		[self getRealTimeServiceInfo];
	}
	return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	CGFloat height;
	
	switch ([indexPath section])
	{
		case 0:
		{
			height = 55;
			break;
		}
		case 1:
		{
			if([indexPath row] == 1)
			{
				height = 55;
			}
			else{
				height = 75;
			}
			break;
		}
			
		case 2:
		{
			height = 150;
			break;
		}
	}
	
	return height;
}

- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if([indexPath section] == 0)
	{
		NSString *telNumber = [[result number] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",telNumber]]];
	}
	
	if([indexPath section] == 1)
	{
		NSString* searchQuery =  [[result location] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
		NSString* urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@", searchQuery];
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
	}

}

- (void) getRealTimeServiceInfo {
	
	NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
	[theRequest setURL:[NSURL URLWithString:result.uri]];
	[theRequest setCachePolicy:LOST_CLIENT_CACHE_POLICY];
	[theRequest setTimeoutInterval:LOST_CLIENT_TIMEOUT_INTERVAL];
	[theRequest setHTTPMethod:@"GET"];
	
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest 
																  delegate:self 
														  startImmediately:YES];
	
	if (connection == nil) {
		UITableViewCell *tmpcell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
		UILabel *value;
		value = (UILabel *)[tmpcell.contentView viewWithTag:2];
		NSString *data = @"no info found";
		CGSize size = [data sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(200,125) lineBreakMode:UILineBreakModeWordWrap];
		value.frame = CGRectMake(85.0, 20.0, size.width, size.height);
		value.text = data;
	}
	else {
		receivedData = [[NSMutableData data] retain];
	}
	
	[theRequest release];
}

- (void) getMQTest {
	
	NSString *xmlData = @"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><Geocode Version=\"1\"><Address><AdminArea1>US</AdminArea1><AdminArea3>PA</AdminArea3><AdminArea5>Mountville</AdminArea5><PostalCode>17554</PostalCode><Street>Hempland Rd</Street></Address><GeocodeOptionsCollection Count=\"0\" /><Authentication Version=\"2\"><Password>xJ2sA3fR</Password><ClientId>81552</ClientId></Authentication></Geocode>";
	
	xmlData = @"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><DoRoute Version=\"2\"><LocationCollection Count=\"2\"><GeoAddress><LatLng><Lat>49.245407</Lat><Lng>-123.036536</Lng></LatLng></GeoAddress><GeoAddress><LatLng><Lat>49.166319</Lat><Lng>-123.941250</Lng></LatLng></GeoAddress></LocationCollection><RouteOptions Version=\"2\"><RouteType>1</RouteType><NarrativeType>-1</NarrativeType><MaxShape>0</MaxShape></RouteOptions><Authentication Version=\"2\"><Password>xJ2sA3fR</Password><ClientId>81552</ClientId></Authentication></DoRoute>";
	
	//NSLog(xmlData);
    NSData *postData = [xmlData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  
	
	NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
	[theRequest setURL:[NSURL URLWithString:@"http://route.dev.mapquest.com:80/mq/mqserver.dll?e=5&"]];
	[theRequest setCachePolicy:LOST_CLIENT_CACHE_POLICY];
	[theRequest setTimeoutInterval:LOST_CLIENT_TIMEOUT_INTERVAL];
	
	[theRequest setHTTPMethod:@"POST"];
	[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
    [theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];  
	[theRequest setValue:@"close" forHTTPHeaderField:@"Connection"];  
    [theRequest setHTTPBody:postData]; 
	
	
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest 
																  delegate:self 
														  startImmediately:YES];
	
	if (connection == nil) {
		NSLog(@"connection failed");
	}
	else {
		receivedData = [[NSMutableData data] retain];
	}
	
	[theRequest release];
}


- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {	
    [receivedData setLength:0];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	UITableViewCell *tmpcell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
	UILabel *value;
	value = (UILabel *)[tmpcell.contentView viewWithTag:2];
	
	NSString *data = @"no info found";
	CGSize size = [data sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(200,125) lineBreakMode:UILineBreakModeWordWrap];
	value.frame = CGRectMake(85.0, 20.0, size.width, size.height);
	value.text = data;
	
	[receivedData release];
	[connection release];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
	UITableViewCell *tmpcell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
	UILabel *value;
	value = (UILabel *)[tmpcell.contentView viewWithTag:2];
	//NSString *data = [[NSString alloc] initWithData:receivedData encoding:1];
	
	NSString *data = @"Average User Rating: 3\n\nAvailable Tables: 2";
	CGSize size = [data sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(200,125) lineBreakMode:UILineBreakModeWordWrap];
	value.frame = CGRectMake(85.0, 20.0, size.width, size.height);
	value.text = data;
	
	[data release];
	[receivedData autorelease];
	[connection release];
}

- (void)routerResponse:(double) distance {
	result.routeDistance = distance;
	UITableViewCell *tmpcell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
	UILabel *value;
	value = (UILabel *)[tmpcell.contentView viewWithTag:2];
	NSString *dist;
	
	if(!useKm){dist = [NSString stringWithFormat:@"%.1f mi",distance];}
	else{dist = [NSString stringWithFormat:@"%.1f km",distance*1.609344];}
	
	
	CGSize size = [dist sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(200,25) lineBreakMode:UILineBreakModeWordWrap];
	value.frame = CGRectMake(85.0, 24.0, size.width, size.height);
	value.text = dist;
}


- (void)routerError:(NSError *)error {
	UITableViewCell *tmpcell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
	UILabel *value;
	value = (UILabel *)[tmpcell.contentView viewWithTag:2];
	
	NSString *errorMsg = @"Error calculating distance";
	CGSize size = [errorMsg sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(200,25) lineBreakMode:UILineBreakModeWordWrap];
	value.frame = CGRectMake(85.0, 24.0, size.width, size.height);
	value.text = errorMsg;
}

- (void)dealloc {
	[tableView release];
	[tabBar release];
	[result release];
	[receivedData release];
    [super dealloc];
}

@end
