#import "AppDelegate.h"
#import "MainViewController.h"

@implementation AppDelegate

@synthesize window;

//START:fetchedResultsController
- (NSFetchedResultsController*)fetchedResultsController
{
  NSManagedObjectContext *context = [self managedObjectContext];
  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  [fetchRequest setEntity:[NSEntityDescription entityForName:@"Recipe" 
                                      inManagedObjectContext:context]];
  // Configure the request's entity, and optionally its predicate.
  NSSortDescriptor *sortDescriptor = nil;
  sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
  NSArray *sortDescriptors = nil;
  sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
  [sortDescriptor release], sortDescriptor = nil;
  [fetchRequest setSortDescriptors:sortDescriptors];
  [sortDescriptors release], sortDescriptors = nil;
  
  NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]
                                            initWithFetchRequest:fetchRequest
                                            managedObjectContext:context
                                            sectionNameKeyPath:nil
                                            cacheName:@"Recipe"];
  [fetchRequest release];
  
  NSError *error = nil;
  BOOL success = [controller performFetch:&error];  
  if (!success) {
    NSLog(@"Error fetching request %@", [error localizedDescription]);
  }
  return [controller autorelease];
}
//END:fetchedResultsController

//START:applicationDidFinishLaunching
- (void)applicationDidFinishLaunching:(UIApplication*)application 
{
  window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  
  NSFetchedResultsController *results = [self fetchedResultsController];
  MainViewController *controller = nil;
  controller = [[MainViewController alloc] initWithFetchController:results];
  
  nav = [[UINavigationController alloc] initWithRootViewController:controller];
  [controller release], controller = nil;
  // Override point for customization after app launch    
  [window addSubview:[nav view]];
  [window makeKeyAndVisible];
}
//END:applicationDidFinishLaunching

//START:documentsFolder
- (NSString*)documentsFolder
{
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                       NSUserDomainMask, YES);
  NSString *filePath = [paths objectAtIndex:0];
  return filePath;
}
//END:documentsFolder

//START:managedObjectModel
- (NSManagedObjectModel*)managedObjectModel 
{
  if (managedObjectModel) return managedObjectModel;
  
  NSString *path = [[NSBundle mainBundle] pathForResource:@"DataModel"
                                                   ofType:@"momd"];
  if (!path) {
    path = [[NSBundle mainBundle] pathForResource:@"DataModel"
                                           ofType:@"mom"];
  }
  NSAssert(path != nil, @"Unable to find DataModel in main bundle");
  NSURL *url = [NSURL fileURLWithPath:path];
  managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
  return managedObjectModel;
}
//END:managedObjectModel

//START:persistentStoreCoordinator
- (NSPersistentStoreCoordinator*)persistentStoreCoordinator;
{
  if (persistentStoreCoordinator) return persistentStoreCoordinator;
  
  NSFileManager *fileManager = [NSFileManager defaultManager];
  NSString *docFolder = [self documentsFolder];
  if (![fileManager fileExistsAtPath:docFolder]) {
    [fileManager createDirectoryAtPath:docFolder attributes:nil];
  }

  NSString *filePath = nil;
  filePath = [docFolder stringByAppendingPathComponent:@"recipes.sqlite"];
  if (![fileManager fileExistsAtPath:filePath]) {
    NSString *defaultDB = [[NSBundle mainBundle] pathForResource:@"recipes" 
                                                          ofType:@"sqlite"];
    NSError *error = nil;
    if (![[NSFileManager defaultManager] copyItemAtPath:defaultDB 
                                                 toPath:filePath 
                                                  error:&error]) {
      NSLog(@"%@:%s Error copying file %@", [self class], _cmd, error);
    }
  }
  
  NSURL *url = [NSURL fileURLWithPath:filePath];
  NSManagedObjectModel *mom = [self managedObjectModel];
  persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] 
                                initWithManagedObjectModel:mom];
  
  NSError *error = nil;
  if ([persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 
                                               configuration:nil 
                                                         URL:url 
                                                     options:nil 
                                                       error:&error]) {
    return persistentStoreCoordinator;
  }
  
  [persistentStoreCoordinator release], persistentStoreCoordinator = nil;
  NSDictionary *ui = [error userInfo];
  if (![ui valueForKey:NSDetailedErrorsKey]) {
    NSLog(@"%@:%s Error adding store %@", [self class], _cmd, 
          [error localizedDescription]);
  } else {
    for (NSError *suberror in [ui valueForKey:NSDetailedErrorsKey]) {
      NSLog(@"%@:%s Error: %@", [self class], _cmd, 
            [suberror localizedDescription]);
    }
  }
  NSAssert(NO, @"Failed to initialize the persistent store");
  return nil;
}
//END:persistentStoreCoordinator

//START:managedObjectContext
- (NSManagedObjectContext*)managedObjectContext
{
  if (managedObjectContext) return managedObjectContext;
  
  NSPersistentStoreCoordinator *coord = [self persistentStoreCoordinator];
  if (!coord) return nil;
  
  managedObjectContext = [[NSManagedObjectContext alloc] init];
  [managedObjectContext setPersistentStoreCoordinator:coord];
  
  return managedObjectContext;
}
//END:managedObjectContext

@end
