/*
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 "ModelCreateViewController.h"
#import "TiltAndSwipeViewController.h"
#import "ModelProcessor.h"

@implementation ModelCreateViewController

@synthesize nameField;
@synthesize errorLabel;
@synthesize modelType;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	[self setTitle: @"Create New Model"];
	
	[nameField setDelegate:self];
	[nameField becomeFirstResponder];
}


/*
// 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 {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


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

/* UITextFieldDelegate */
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	if (textField == nameField) {
		NSString *templateName;
		// this is too frsgile for my taste
		if ([modelType selectedSegmentIndex]==0) {
			templateName = @"Sample Airplane (Futaba)";
		} else {
			templateName = @"Sample Car";
		}
		ModelProcessor *template = [[ModelProcessor alloc] initWithFilePath:
									[[NSBundle mainBundle] pathForResource: templateName
																	ofType: MODEL_CONFIG_FILE_EXTENSION]];
		NSString* copyError = nil;
        ModelProcessor* newProc = [template copy:[textField text] error: &copyError];
		if (!newProc) {
			[errorLabel setTitle:copyError forState:UIControlStateNormal];
			[errorLabel setHidden: NO];
		} else {
			[textField resignFirstResponder];
			[errorLabel setTitle:@"" forState: UIControlStateNormal];
			[errorLabel setHidden: YES];
            
            UIViewController* root = [[[self navigationController] viewControllers] objectAtIndex:0];
            if ([root isKindOfClass:[TiltAndSwipeViewController class]]) {
                [[(TiltAndSwipeViewController*)root processor] stopTransmission];
            }
            
            TiltAndSwipeViewController *new = [(TiltAndSwipeViewController *)[TiltAndSwipeViewController alloc] initWithProcessor:newProc];
            
            [[self navigationController] setViewControllers: [NSArray arrayWithObjects: new, self, nil] animated:NO];
            
            // remeber this model for next session
            [[NSFileManager defaultManager] removeItemAtPath:[ModelProcessor pathOfSymlinkToLastModelFromPreviousSession] error:NULL];
            [[NSFileManager defaultManager] createSymbolicLinkAtPath:[ModelProcessor pathOfSymlinkToLastModelFromPreviousSession]
                                                 withDestinationPath:[[newProc filePath] lastPathComponent] error:NULL];
            
            [self.navigationController popViewControllerAnimated:YES];
            [new release];

		}
	}
	return YES;
}

@end
