//
//  Database+Favorites.m
//  DrivoMeter
//
//  Created by Triin Uudam on 5/3/12.
//  Copyright (c) 2012 Mobi Solutions OÜ. All rights reserved.
//

#import "Database+Favorites.h"
#import "Favorite.h"
#import "Constants.h"

@implementation Database (Favorites)

- (Favorite *)addNewFavoriteWithDistance:(double)distance purpose:(NSString *)purpose isBusiness:(BOOL)business {
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"distance = %@ && purpose = %@ && isBusiness = %@", [NSNumber numberWithDouble:distance], purpose, [NSNumber numberWithBool:business]];
  
  Favorite *favorite = [self findCoreObjectNamed:@"Favorite" withPredicate:predicate];
  if (favorite == nil) {
    MSLog(@"new favorite");
    favorite = [Favorite insertInManagedObjectContext:self.managedObjectContext];
    [favorite setDistanceValue:distance];
    [favorite setPurpose:purpose];
    [favorite setIsBusinessValue:business];
    [self saveContext];
  }  
  
  return favorite;
}

- (void)deleteFavorite:(Favorite *)favorite {
  [self.managedObjectContext deleteObject:favorite];
  [self saveContext];
}

- (void)deleteFavoriteWithTrip:(Trip *)trip {
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ IN trips", trip];
  Favorite *favorite = [self findCoreObjectNamed:@"Favorite" withPredicate:predicate];
  [self deleteFavorite:favorite];
}

- (void)addTrip:(Trip *)trip toFavorite :(Favorite *)favorite {
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"distance = %@ && purpose = %@ && isBusiness = %@", [NSNumber numberWithDouble:trip.distanceValue], trip.purpose, [NSNumber numberWithBool:trip.isBusinessValue]];
  NSArray *tripsArray = [self listCoreObjectsNamed:@"Trip" withPredicate:predicate];
  for (Trip *trip in tripsArray) {
    [trip setFavorite:favorite];
  }
}

- (NSFetchedResultsController *)fetchedResultsControllerForFavorites {
  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  NSEntityDescription *entity = [NSEntityDescription entityForName:@"Favorite" inManagedObjectContext:self.managedObjectContext];
  [fetchRequest setEntity:entity];
  NSSortDescriptor *activeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"purpose" ascending:NO];
  NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:activeSortDescriptor, nil];
  [fetchRequest setSortDescriptors:sortDescriptors];
  
  NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]
                                            initWithFetchRequest:fetchRequest
                                            managedObjectContext:[self managedObjectContext]
                                            sectionNameKeyPath:nil cacheName:nil];
  
  return controller;
}

@end
