//
//  ModelCreateViewController.m
//  iPhly
//
//  Created by Ari Krupnik on 6/2/10.
//  Copyright 2010 lib.aero. All rights reserved.
//

#import "ModelCreateViewController.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 = [template copy:[textField text]];
		if (copyError) {
			[errorLabel setTitle:copyError forState:UIControlStateNormal];
			[errorLabel setHidden: NO];
		} else {
			[textField resignFirstResponder];
			[errorLabel setTitle:@"" forState: UIControlStateNormal];
			[errorLabel setHidden: YES];
			[[self navigationController] popViewControllerAnimated:YES];
		}
	}
	return YES;
}

@end
