//
//  Database.m
//  Parkimine
//
//  Created by Triin Uudam on 8/31/11.
//

#import "Database.h"

@interface Database (Private)

- (NSURL *)applicationDocumentsDirectory;

- (NSManagedObjectModel *)managedObjectModel;

@end

@implementation Database

- (id)initWithPersistentStoreCoordinator:(NSPersistentStoreCoordinator *)coordinator {
  self = [self init];
  
  if (self != nil) {
    persistentStoreCoordinator_ = coordinator;
  }
  
  return self;
}

- (id)initWithStoreURL:(NSURL *)storeURL storeType:(NSString *)storeType {
  self = [super init];
  
  if (self != nil) {
    storeURL_ = storeURL;
    storeType_ = [storeType copy];
  }
  
  return self;
}

- (id)init {
  return [self initWithStoreURL:[[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Drivo.sqlite"] storeType:NSSQLiteStoreType];
}



- (int)countCoreObjectsNamed:(NSString *)modelName {
  return [self countCoreObjectsNamed:modelName withPredicate:nil];
}

- (int)countCoreObjectsNamed:(NSString *)modelName withPredicate:(NSPredicate *)predicate {
  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  NSEntityDescription *entity = [NSEntityDescription entityForName:modelName inManagedObjectContext:self.managedObjectContext];
  [fetchRequest setEntity:entity];
  [fetchRequest setIncludesSubentities:NO];
  
  if (predicate != nil) {
    [fetchRequest setPredicate:predicate];
  }
  
  NSError *error = nil;
  NSUInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
  
  if (error != nil) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
  }
  
  
  return count;
}

- (id)findCoreObjectNamed:(NSString *)modelName withPredicate:(NSPredicate *)predicate {
  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  NSEntityDescription *entity = [NSEntityDescription entityForName:modelName inManagedObjectContext:self.managedObjectContext];
  [fetchRequest setEntity:entity];
  [fetchRequest setPredicate:predicate];
  
  NSError *error = nil;
  NSArray *objects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
  
  if (error != nil) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
  }
  
  
  if ([objects count] != 1) {
    return nil;
  } else {
    return [objects objectAtIndex:0];
  }
}

- (NSArray *)listCoreObjectsNamed:(NSString *)modelName {
  return [self listCoreObjectsNamed:modelName withPredicate:nil];
}

- (NSArray *)listCoreObjectsNamed:(NSString *)modelName withPredicate:(NSPredicate *)predicate {
  return [self listCoreObjectsNamed:modelName withPredicate:predicate usingSortDescriptors:nil];  
}

- (NSArray *)listCoreObjectsNamed:(NSString *)modelName withPredicate:(NSPredicate *)predicate usingSortDescriptors:(NSArray *)sortDescriptors {
  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  NSEntityDescription *entity = [NSEntityDescription entityForName:modelName inManagedObjectContext:self.managedObjectContext];
  [fetchRequest setEntity:entity];
  
  if (predicate != nil) {
    [fetchRequest setPredicate:predicate];
  }
  
  if (sortDescriptors != nil) {
    [fetchRequest setSortDescriptors:sortDescriptors];
  }
  
  NSError *error = nil;
  NSArray *objects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
  
  if (error != nil) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
  }
  
  
  return objects;
}

- (void)deleteObject:(NSManagedObject *)object {
  [self deleteObject:object saveAfter:TRUE];
}

- (void)deleteObject:(NSManagedObject *)object saveAfter:(BOOL)saveAfter {
  if (object == nil) {
    return;
  }
  
  [[self managedObjectContext] deleteObject:object];
  if (saveAfter) {
    [self saveContext];
  }
}

- (NSFetchedResultsController *)fetchedResultsControllerUsingFetchRequest:(NSFetchRequest *)request {
  return [[NSFetchedResultsController alloc]
           initWithFetchRequest:request
           managedObjectContext:[self managedObjectContext]
           sectionNameKeyPath:nil cacheName:nil];
}

- (NSExpressionDescription *)descriptionWithPath:(NSString *)keyPath function:(NSString *)function resultName:(NSString *)name type:(NSAttributeType)type {
  NSExpression *pathExpression = [NSExpression expressionForKeyPath:keyPath];
  NSExpression *functionExpression = [NSExpression expressionForFunction:function arguments:[NSArray arrayWithObject:pathExpression]];
  NSExpressionDescription *description = [[NSExpressionDescription alloc] init];
  [description setName:name];
  [description setExpression:functionExpression];
  [description setExpressionResultType:type];
  return description;
}


- (void)saveContext {
  NSLog(@"saveContext");
  NSError *error = nil;
  NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
  if (managedObjectContext != nil) {
    if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
      /*
       Replace this implementation with code to handle the error appropriately.
       
       abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
       */
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
      abort();
    }
  }
}

#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.
 */
- (NSManagedObjectContext *)managedObjectContext {
  if (managedObjectContext_ != nil) {
    return managedObjectContext_;
  }
  
  NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
  if (coordinator != nil) {
    managedObjectContext_ = [[NSManagedObjectContext alloc] init];
    [managedObjectContext_ setPersistentStoreCoordinator:coordinator];
    [managedObjectContext_ setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];
  }
  return managedObjectContext_;
}

/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created from the application's model.
 */
- (NSManagedObjectModel *)managedObjectModel {
  if (managedObjectModel_ != nil) {
    return managedObjectModel_;
  }
  NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Drivo" withExtension:@"momd"];
  managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
  return 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.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
  if (persistentStoreCoordinator_ != nil) {
    return persistentStoreCoordinator_;
  }
  
  NSError *error = nil;
  persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
  if (![persistentStoreCoordinator_ addPersistentStoreWithType:storeType_ configuration:nil URL:storeURL_ options:nil error:&error]) {
    /*
     Replace this implementation with code to handle the error appropriately.
     
     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
     
     Typical reasons for an error here include:
     * The persistent store is not accessible;
     * The schema for the persistent store is incompatible with current managed object model.
     Check the error message to determine what the actual problem was.
     
     
     If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
     
     If you encounter schema incompatibility errors during development, you can reduce their frequency by:
     * Simply deleting the existing store:
     [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
     
     * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
     [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
     
     Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
     
     */
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
  }
  
  return persistentStoreCoordinator_;
}

#pragma mark - Application's Documents directory

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory {
  return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

@end
