//
//  DatabaseShoppingListAppDelegate.m
//  DatabaseShoppingList
//
//  Created by Chris Adamson on 3/27/09.
//  Copyright Subsequently and Furthermore, Inc. 2009. All rights reserved.
//
//
//  Licensed with the Apache 2.0 License
//  http://apache.org/licenses/LICENSE-2.0
//


#import "DatabaseShoppingListAppDelegate.h"


@implementation DatabaseShoppingListAppDelegate

@synthesize window;
@synthesize tabBarController;
@synthesize dbFilePath;


NSString *DATABASE_RESOURCE_NAME = @"shopping";
NSString *DATABASE_RESOURCE_TYPE = @"db";
NSString *DATABASE_FILE_NAME = @"shopping.db";

// NSString *dbFilePath;


- (BOOL) initializeDb {
	NSLog (@"initializeDB");
	// look to see if DB is in known location (~/Documents/$DATABASE_FILE_NAME)
	//START:code.DatabaseShoppingList.findDocumentsDirectory
	NSArray *searchPaths =
		NSSearchPathForDirectoriesInDomains
		(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentFolderPath = [searchPaths objectAtIndex: 0];
	dbFilePath = [documentFolderPath stringByAppendingPathComponent:
				  DATABASE_FILE_NAME];
	//END:code.DatabaseShoppingList.findDocumentsDirectory
	[dbFilePath retain];
	//START:code.DatabaseShoppingList.copyDatabaseFileToDocuments
	if (! [[NSFileManager defaultManager] fileExistsAtPath: dbFilePath]) {
		// didn't find db, need to copy
		NSString *backupDbPath = [[NSBundle mainBundle]
			  pathForResource:DATABASE_RESOURCE_NAME
			  ofType:DATABASE_RESOURCE_TYPE];
		if (backupDbPath == nil) {
			// couldn't find backup db to copy, bail
			return NO;
		} else {
			BOOL copiedBackupDb = [[NSFileManager defaultManager]
			   copyItemAtPath:backupDbPath
			   toPath:dbFilePath
			   error:nil];
			if (! copiedBackupDb) {
				// copying backup db failed, bail
				return NO;
			}
		}
	}
	return YES;
	//END:code.DatabaseShoppingList.copyDatabaseFileToDocuments
	NSLog (@"bottom of initializeDb");
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {

	// copy the database from the bundle if necessary
	if (! [self initializeDb]) {
		// TODO: alert the user!
		NSLog (@"couldn't init db");
		return;
	}	
	
    // Add the tab bar controller's current view as a subview of the window
    [window addSubview:tabBarController.view];
}


/*
// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
}
*/

/*
// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed {
}
*/


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

@end

