//
//  ConferenceAppDelegate.m
//  Conference
//
//  Created by Bill Dudney on 5/11/09.
//  Copyright Gala Factory Software LLC 2009. All rights reserved.
//
//
//  Licensed with the Apache 2.0 License
//  http://apache.org/licenses/LICENSE-2.0
//

#import "ConferenceAppDelegate.h"
#import "RootViewController.h"


@implementation ConferenceAppDelegate

@synthesize window;
@synthesize navigationController;


#pragma mark -
#pragma mark Application lifecycle

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    
    // Override point for customization after app launch    

	RootViewController *rootViewController = (RootViewController *)[navigationController topViewController];
	rootViewController.managedObjectContext = self.managedObjectContext;
	
	[window addSubview:[navigationController view]];
    [window makeKeyAndVisible];
}

/**
 applicationWillTerminate: saves changes in the application's managed object context before the application terminates.
 */
- (void)applicationWillTerminate:(UIApplication *)application {
	
    NSError *error;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
			// Handle error.
			NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
			exit(-1);  // Fail
        } 
    }
}


#pragma mark -
#pragma mark Saving

/**
 Performs the save action for the application, which is to send the save:
 message to the application's managed object context.
 */
- (IBAction)saveAction:(id)sender {
	
    NSError *error;
    if (![[self managedObjectContext] save:&error]) {
		// Handle error
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		exit(-1);  // Fail
    }
}


#pragma mark -
#pragma mark Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
//START:code01.app.delegate.managedObjectContext
- (NSManagedObjectContext *) managedObjectContext {
  if (managedObjectContext != nil) {
    return managedObjectContext;
  }
	
  NSPersistentStoreCoordinator *coordinator = 
          [self persistentStoreCoordinator];
  if (coordinator != nil) {
    managedObjectContext = [[NSManagedObjectContext alloc] init];
    [managedObjectContext setPersistentStoreCoordinator: coordinator];
  }
  return managedObjectContext;
}
//END:code01.app.delegate.managedObjectContext


/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created by merging all of the models found in the application bundle.
 */
//START:code01.app.delegate.managedObjectModel
- (NSManagedObjectModel *)managedObjectModel {
  if (managedObjectModel != nil) {
    return managedObjectModel;
  }
  managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] 
                        retain];
  return managedObjectModel;
}
//END:code01.app.delegate.managedObjectModel


/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
//START:code01.app.delegate.persistentStoreCoordinator
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
  if (persistentStoreCoordinator != nil) {
    return persistentStoreCoordinator;
  }
	
  NSURL *storeUrl = [NSURL fileURLWithPath: 
                     [[self applicationDocumentsDirectory]
                      stringByAppendingPathComponent: @"Conference.sqlite"]];
	
	NSError *error = nil;
  persistentStoreCoordinator = //<label id="code.app.del.psc.create"/>
  [[NSPersistentStoreCoordinator alloc] 
   initWithManagedObjectModel: [self managedObjectModel]];
  if (![persistentStoreCoordinator //<label id="code.app.del.psc.config"/>
        addPersistentStoreWithType:NSSQLiteStoreType 
        configuration:nil 
        URL:storeUrl 
        options:nil 
        error:&error]) {
    // Handle error
  }    
	
  return persistentStoreCoordinator;
}
//END:code01.app.delegate.persistentStoreCoordinator


#pragma mark -
#pragma mark Application's documents directory

/**
 Returns the path to the application's documents directory.
 */
//START:code01.app.delegate.applicationDocumentsDirectory
- (NSString *)applicationDocumentsDirectory {
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                       NSUserDomainMask,
                                                       YES);
  NSString *basePath = nil;
  if([paths count] > 0) {
    basePath = [paths objectAtIndex:0];
  }
  return basePath;
}
//END:code01.app.delegate.applicationDocumentsDirectory

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
	
    [managedObjectContext release];
    [managedObjectModel release];
    [persistentStoreCoordinator release];
    
	[navigationController release];
	[window release];
	[super dealloc];
}


@end

