//
//  RootViewController.m
//  iPhly
//
//  Created by Ari Krupnik on 4/27/10.
//  Copyright lib.aero 2010. All rights reserved.
//

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


@implementation RootViewController


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

- (void)viewDidLoad {
    [super viewDidLoad];
	
	[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:NO];
		[tsc release];
		[proc release];
	}
}



 - (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	 
	[modelPaths release];
	modelPaths = [[ModelProcessor allModelPaths] retain];
	[[self tableView] reloadData];
}


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


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
    }
    
	// Configure the cell.
	
	NSString *path = [modelPaths objectAtIndex: [indexPath row]];	
	NSString *modelName = [[path lastPathComponent] stringByDeletingPathExtension];
	[[cell textLabel] setText: modelName];
	
    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

