

#import "ArchiversAppDelegate.h"
#import "ArchiversViewController.h"

@implementation ArchiversAppDelegate

@synthesize window;
@synthesize viewController;
@synthesize personArray;
@synthesize dataFilePath;

- (id) init {
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *path = [documentsDirectory stringByAppendingPathComponent:@"people.dat"];
	[self setDataFilePath:path];
	
	NSFileManager *fileManager = [NSFileManager defaultManager];
	if([fileManager fileExistsAtPath:dataFilePath]) {
		//open it and read it 
		NSLog(@"data file found. reading into memory");
		NSMutableData *theData;
		NSKeyedUnarchiver *decoder;
		NSMutableArray *tempArray;
		
		theData = [NSData dataWithContentsOfFile:dataFilePath];
		decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];
		tempArray = [decoder decodeObjectForKey:@"personArray"];
		[self setPersonArray:tempArray];
		[decoder finishDecoding];
		[decoder release];		
	} else {
		NSLog(@"no file found. creating empty array");
		personArray = [[NSMutableArray alloc] init];
	}
	
	return self;
}


- (void)applicationDidFinishLaunching:(UIApplication *)application {	
	
	// Override point for customization after app launch	
    [window addSubview:viewController.view];
	[window makeKeyAndVisible];
}

- (void) applicationWillTerminate:(UIApplication *)application {
	NSMutableData *theData;
	NSKeyedArchiver *encoder;
	
	theData = [NSMutableData data];
	encoder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:theData];
	
	[encoder encodeObject:personArray forKey:@"personArray"];
	[encoder finishEncoding];
	
	[theData writeToFile:dataFilePath atomically:YES];
	[encoder release];
}
	


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


@end
