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

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

@implementation Database (User)

- (void)findOrCreateUserWithName:(NSString *)name email:(NSString *)email company:(NSString *)company carNumber:(NSString *)carNumber businessRegisterCode:(NSString *)registerCode {
  
  User *user = [self findCoreObjectNamed:@"User" withPredicate:nil];
  MSLog(@"User %@", user);
  if (user == nil) {
    user = [User insertInManagedObjectContext:[self managedObjectContext]];
  }  
  [user setName:name];
  [user setEmail:email];
  [user setCompany:company];
  [user setCarNumber:carNumber];
  [user setBusinessRegisterCode:registerCode];
  
  [self saveContext];
}

- (User *)currentUser {
  User *user = [self findCoreObjectNamed:@"User" withPredicate:nil];
  if (user == nil) {
    MSLog(@"new user");
    user = [User insertInManagedObjectContext:self.managedObjectContext];
    [self saveContext];
  }  
  return user;
}

- (void)deleteUser {
  [self deleteObject:[self findCoreObjectNamed:@"User" withPredicate:nil]];
  [self saveContext];
}

@end
