//
//  RootViewController.m
//  Free Name
//
//  Created by Willem Laurentz Middelkoop on 13-03-11.
//  Copyright 2011 WMIT. All rights reserved.
//

#import "RootViewController.h"
#import "ResultViewController.h"
#import "NameCheckResult.h"
#import "NameCheck.h"
#import "NameCheckResultInterfaceParser.h"

@implementation RootViewController


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];

	listOfItems = [[NSMutableArray alloc] init];
	
	
	self.navigationItem.titleView = searchBar;
	self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:178/255.0 green:210/255.0 blue:52/255.0 alpha:1.0]; 
	
	self.tableView.backgroundColor =[UIColor clearColor];
	self.tableView.backgroundView = backgroundView;
	self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	
	searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	searchBar.tintColor = [UIColor colorWithRed:178/255.0 green:210/255.0 blue:52/255.0 alpha:1.0]; 
	
	// Set the keyboard return button to "Done"
	NSArray *searchBarSubviews = [searchBar subviews] ;
	for(id searchBarSubview in searchBarSubviews) {
		if([searchBarSubview isKindOfClass:[UITextField class]]) {
			[(UITextField*)searchBarSubview setReturnKeyType:UIReturnKeyGo];
		}
	}
	
	
	self.navigationItem.leftBarButtonItem = buttonReset;// [[UIBarButtonItem alloc]initWithTitle:@"Reset" style:UIBarButtonSystemItemCancel target:self action:@selector(resetResults:)];
	
	//self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRewind
	//																	   target:nil
	//																					  action:nil];
	 
	
	self.navigationItem.backBarButtonItem = 
	
	
	[[UIBarButtonItem alloc] initWithTitle:@"◀◀"
									 style: UIBarButtonItemStyleBordered
									target:nil
									action:nil];
	 
	[searchBar becomeFirstResponder];
	
}

-(void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {
	// the searchbar begin editing text
}


- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
	if([searchBar.text length] > 0){
		[self check];
	}
	[searchBar resignFirstResponder];	
}


- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
	
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations.
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
 */

-(void)buttonReset_click:(id)sender{
	if([searchBar.text length]>0){
		searchBar.text = @"";
		[searchBar becomeFirstResponder];
	}else{
		[searchBar becomeFirstResponder];
		self.tableView.scrollEnabled = NO;
		[listOfItems removeAllObjects];
		[self.tableView reloadData];
		self.tableView.scrollEnabled = YES;
		self.tableView.backgroundView = backgroundView;
		self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
		
		
	}
}


-(void)check{
	[self startCheckThread];
}

- (void) startCheckThread {
	// Fire up a thread to perform the suggestion work in the background
	[NSThread detachNewThreadSelector:@selector(doCheckWork) toTarget:self withObject:nil];
	
	[searchBar setHidden:YES];
	[buttonReset setEnabled:NO];
	[self.view addSubview:progressView];
//	lblProgressViewKeyword.text = self.searchText;
}


- (void) doCheckWork {
	
/*	Reachability *r = [Reachability reachabilityWithHostName:@"server.shopcat.eu"];
	NetworkStatus internetStatus = [r currentReachabilityStatus];
	if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)){
		[self performSelectorOnMainThread:@selector(showProgressViewReachability) withObject:nil waitUntilDone:false];
		
		while((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)){
			[NSThread sleepForTimeInterval:2.0];
			internetStatus = [r currentReachabilityStatus];	
		}
	}
	
	// Do the GPS thing
	ShopcatAppDelegate *appDelegate = (ShopcatAppDelegate *) [[UIApplication sharedApplication] delegate];
	
	if(appDelegate.bestEffortAtLocation == nil || appDelegate.bestEffortAtLocation.horizontalAccuracy > 200){
		[self performSelectorOnMainThread:@selector(showProgressViewGPS) withObject:nil waitUntilDone:false];
		
		while(appDelegate.bestEffortAtLocation == nil || appDelegate.bestEffortAtLocation.horizontalAccuracy > 200){
			[NSThread sleepForTimeInterval:2.0];
		}
	}*/
	
	
	//while(appDelegate.bestEffortAtLocation
	
	
	// [self performSelectorOnMainThread:@selector(showProgressViewSearching) withObject:nil waitUntilDone:false];
	
	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	//[listOfItems removeAllObjects];
	
	
	
	NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
																				  NULL,
																				  (CFStringRef)searchBar.text,
																				  NULL,
																				  (CFStringRef)@"!*'();:@&=+$,/?%#[]",
																				  kCFStringEncodingUTF8 );
	
	
	NSString *soapMessage = [NSString stringWithFormat:
							 @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
							 "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
							 "<soap:Body>\n"
							 "<getNameCheckResults xmlns=\"http://freename.wmit.nl/\">\n"
							 "<name>%@</name>\n"
							 "</getNameCheckResults>\n"
							 "</soap:Body>\n"
							 "</soap:Envelope>\n", encodedString
							 ];
    [encodedString release];
	
	//NSURL *url = [NSURL URLWithString:@"http://192.168.1.36:5004/api/v001/FreeNameService.asmx"];
	NSURL *url = [NSURL URLWithString:@"http://freename.wmit.nl/api/v001/FreeNameService.asmx"];
	
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
	NSString *messageLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
	
	[request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[request addValue: @"http://freename.wmit.nl/getNameCheckResults" forHTTPHeaderField:@"SOAPAction"];
	[request addValue: messageLength forHTTPHeaderField:@"Content-Length"];
	[request setHTTPMethod:@"POST"];
	[request setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
	
	NSHTTPURLResponse *response;
	NSError *error;
	NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	
	NameCheckResultInterfaceParser *dataParser = [NameCheckResultInterfaceParser alloc];
	dataParser.name = searchBar.text;
	if([dataParser parseData:data]){
		//if(currentSuggestionCount == suggestionCount){
			[self performSelectorOnMainThread:@selector(reloadChecks:) withObject:[dataParser nameCheck] waitUntilDone:YES];
		//}else{
		//	NSLog(@"ignored 'late' suggestion");			
		//}
	}
	
	//suggesting = FALSE;
    [dataParser release];
	[pool release];
} 

-(void)reloadChecks:(NameCheck *)nameCheck{
	self.tableView.scrollEnabled = NO;
	//[listOfItems removeAllObjects];
	[listOfItems addObject:nameCheck];// addObjectsFromArray:newItems];
	
	[self.tableView reloadData];
	
	//self.navigationItem.title = searchText; 
	
	if([listOfItems count]>0){ // results!
		self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;// UITableViewCellSeparatorStyleNone;
		self.tableView.backgroundView = backgroundResultsView;
		
		NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:([listOfItems count] - 1) inSection:0];
        [[self tableView] scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
		
		
		//	[self setViewAsResultMode];
		
	}
	
	self.tableView.scrollEnabled = YES;
	[progressView removeFromSuperview];	
	[searchBar setHidden:NO];
	[buttonReset setEnabled:YES];
	
	[searchBar resignFirstResponder];
	
	ResultViewController *resultViewController = [[ResultViewController alloc] initWithNibName:@"ResultView" bundle:[NSBundle mainBundle]];
	resultViewController.nameCheck = nameCheck;
	[self.navigationController pushViewController:resultViewController animated:YES];
	[resultViewController release];
}



#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [listOfItems count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	static NSString *CellIdentifier = @"Cell";
    
	// Dequeue or create a cell of the appropriate type.
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		cell.selectionStyle =  UITableViewCellSelectionStyleBlue;
		
		//Indentation Code.
		cell.indentationLevel = 1;
		cell.indentationWidth = 30;
		
		CGRect frame; frame.origin.x = 5; frame.origin.y = 5; frame.size.height = 32; frame.size.width = 32;
		
		//Print Icon
		UIImageView *imgLabel = [[UIImageView alloc] initWithFrame:frame];
		imgLabel.tag = 1000;
		[cell.contentView addSubview:imgLabel];
		[imgLabel release];        
		
	}
	
	NameCheck *nameCheck = [listOfItems objectAtIndex:indexPath.row];
	
	cell.textLabel.text = nameCheck.name;
	//cell.detailTextLabel.text = result.isAvailable;
	
	
	//Setup Pic in Cell
	UIImageView *imageView = (UIImageView *) [cell.contentView viewWithTag:1000];
	imageView.image = nil;
	
	
	if([nameCheck.isAvailable isEqual:@"true"]){
		imageView.image = [UIImage imageNamed:@"available.png"]; // set the image for the imageview
	}else{ 
		imageView.image = [UIImage imageNamed:@"not-available.png"]; // set the image for the imageview
	}
	
	return cell;
	
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	NameCheck *selectedCheck =  [listOfItems objectAtIndex:indexPath.row];
	[searchBar resignFirstResponder];
	
	ResultViewController *resultViewController = [[ResultViewController alloc] initWithNibName:@"ResultView" bundle:[NSBundle mainBundle]];
	resultViewController.nameCheck = selectedCheck;
	[self.navigationController pushViewController:resultViewController animated:YES];
    [resultViewController release];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

