/*
iPhly: Radio Control on the iPhone

Copyright (C) 2010-2011 Ari Krupnik & Associates

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License V2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#import "RootViewController.h"
#import "ModelProcessor.h"
#import "TiltAndSwipeViewController.h"
#import "FlyByTouchViewController.h"
#import "DriveByTouchViewController.h"
#import "ModelCreateViewController.h"
#import "util.h"
#import "util_m.h"


@implementation RootViewController


- (NSString *) pathOfSymlinkToLastModelFromPreviousSession {
	//NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	return [[ModelProcessor modelsDir] stringByAppendingPathComponent: @"last-model-from-previous-session.lnk"];
}

- (UIImage *) genericAirplaneIcon {
	static UIImage *img = nil;
	if (!img)
		img = [UIImage imageNamed: @"Attitude_Indicator-44.png"];
	return img;
}
- (UIImage *) genericCarIcon {
	static UIImage *img = nil;
	if (!img)
		img = [UIImage imageNamed: @"SteeringWheel-44.png"];
	return img;
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	dummyCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
	
	[self setTitle: @"iPhly"];
	
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addModel)]autorelease];
	
	// load the last model from previous session, if there is one
	NSString *path = [[self pathOfSymlinkToLastModelFromPreviousSession] stringByResolvingSymlinksInPath];
	ModelProcessor *proc = [[ModelProcessor alloc] initWithFilePath: path];
	
	// if the symlink is not present or is invalid, pick the first model on the list
	if (!proc && [[ModelProcessor allModelPaths] count]) {
		// it's possible for the user to delete all models and have an empty list
		proc = [[ModelProcessor alloc] initWithFilePath:[[ModelProcessor allModelPaths] objectAtIndex:0]];
	}
	
	//
	if (proc) {
		TiltAndSwipeViewController *tsc = [(TiltAndSwipeViewController *)[TiltAndSwipeViewController alloc] initWithProcessor:proc];
		[self.navigationController pushViewController:tsc animated:YES];
		[tsc release];
		[proc release];
	}
}



- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	
	[modelPaths release];
	modelPaths = [[ModelProcessor allModelPaths] retain];
	
	[cells release];
	cells = [[NSMutableArray alloc] initWithCapacity:[modelPaths count]];
	for (NSString *path in modelPaths) {
		[cells addObject:dummyCell];
	}
	
	[[self tableView] reloadData];
}


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


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

- (void)viewDidUnload {
	// Release anything that can be recreated in viewDidLoad or on demand.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [cells objectAtIndex:[indexPath row]];
    if (cell == dummyCell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
		[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
		
		NSString *path = [modelPaths objectAtIndex: [indexPath row]];	
		
		ModelProcessor *proc = [[ModelProcessor alloc] initWithFilePath: path];
		[[cell textLabel] setText: [proc name]];
		
		UIImage *img = [proc image];
		if (img) {
			img = thumbNail(img, [cell frame].size.height, 0);
		} else {
			img = [proc isCar] ? [self genericCarIcon] : [self genericAirplaneIcon];
		}
		[[cell imageView] setImage:img];
		[proc release];
		
		[cells insertObject:cell atIndex:[indexPath row]];
	}	
    return cell;
}


// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	NSString *path = [modelPaths objectAtIndex: [indexPath row]];
	ModelProcessor *proc = [[[ModelProcessor alloc] initWithFilePath: path] autorelease];
	TiltAndSwipeViewController *tsc = [(TiltAndSwipeViewController *)[TiltAndSwipeViewController alloc] initWithProcessor:proc];
	
	// remeber this model for next session
	[[NSFileManager defaultManager] removeItemAtPath:[self pathOfSymlinkToLastModelFromPreviousSession] error:NULL];
	[[NSFileManager defaultManager] createSymbolicLinkAtPath:[self pathOfSymlinkToLastModelFromPreviousSession] withDestinationPath:[path lastPathComponent] error:NULL];
	
	[self.navigationController pushViewController:tsc animated:YES];
	[tsc release];
}



/*
// 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;
}
*/


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

- (void) addModel {
	ModelCreateViewController *mcvc = [[ModelCreateViewController alloc] initWithNibName:nil bundle:nil];
	[self.navigationController pushViewController:mcvc animated:YES];
	[mcvc release];
}

@end

