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

#import "Database+Odometer.h"
#import "Odometer.h"
#import "Constants.h"

@implementation Database (Odometer)


- (void)findOrAddNewOdodmeterWithState:(double)state date:(NSDate *)date {
  Odometer *odometer = [self findCoreObjectNamed:@"Odometer" withPredicate:nil];
  if (odometer == nil) {
    odometer = [Odometer insertInManagedObjectContext:self.managedObjectContext];
  }  
  [odometer setStateValue:state];
  [odometer setDate:date];
  [self saveContext];
}

- (void)updateOdometerStateWith:(double)addedDistance {
  MSLog(@"update odometer state");
  Odometer *odometer = [self findCoreObjectNamed:@"Odometer" withPredicate:nil];
  if (odometer == nil) {
    odometer = [Odometer insertInManagedObjectContext:self.managedObjectContext];
  }  
  odometer.stateValue += addedDistance;
  MSLog(@"updated odometer state %.1f", odometer.stateValue);
  [self saveContext];
}

- (double)newestOdometerState {
 Odometer *odometer = [self findCoreObjectNamed:@"Odometer" withPredicate:nil];
  if (odometer == nil) {
    odometer = [Odometer insertInManagedObjectContext:self.managedObjectContext];
  }  
  return odometer.stateValue;
}

@end
