#import "MyDocument.h"
#import "DocumentPreferences.h"

@implementation MyDocument

@synthesize preferences = _preferences;

- (id)init 
{
  if (!(self = [super init])) return nil;
  
  _preferences = [[DocumentPreferences alloc] initWithDocument:self];
  
  //START:setDefaults
  NSMutableDictionary *defaults = [NSMutableDictionary dictionary];
  [defaults setValue:[NSNumber numberWithBool:YES] forKey:@"default1"];
  [defaults setValue:@"DefaultValue2" forKey:@"default2"];
  [defaults setValue:@"DefaultValue3" forKey:@"default3"];
  [_preferences setDefaults:defaults];
  //END:setDefaults
  
  return self;
}

- (NSString *)windowNibName 
{
  return @"MyDocument";
}

- (void)windowControllerDidLoadNib:(NSWindowController *)windowController 
{
  [super windowControllerDidLoadNib:windowController];
  // user interface preparation code
  
  if ([self managedObjectContext]) NSLog(@"Context exists");
  else NSLog(@"%@:%s Context is nil", [self class], _cmd);
  
  //START:GoodRead
  if ([[[self defaults] valueForKey:@"default1"] boolValue]) {
    //Do something clever
  }
  //END:GoodRead
  //START:GoodWrite
  [[self defaults] setValue:@"New Value" forKey:@"newKey"];
  //END:GoodWrite
}

//START:BadExample
- (void)clunkyParameterAccess
{
  NSManagedObjectContext *moc = [self managedObjectContext];
  NSFetchRequest *request = [[NSFetchRequest alloc] init];
  [request setEntity:[NSEntityDescription entityForName:@"parameter"
                                 inManagedObjectContext:moc]];

  [request setPredicate:[NSPredicate predicateWithFormat:@"name == %@", 
                         @"default1"]];
  
  NSError *error = nil;
  
  NSManagedObject *param = [[moc executeFetchRequest:request 
                                               error:&error] lastObject];
  if (error) {
    NSLog(@"%@:%s Error fetching param: %@", [self class], _cmd, error);
    return;
  }
  
  NSLog(@"%@:%s Parameter value %@", [self class], _cmd, 
        [param valueForKey:@"value"]);
}
//END:BadExample

//START:BadWrite
- (void)clunkyParameterWrite
{
  NSManagedObjectContext *moc = [self managedObjectContext];
  NSFetchRequest *request = [[NSFetchRequest alloc] init];
  [request setEntity:[NSEntityDescription entityForName:@"parameter"
                                 inManagedObjectContext:moc]];
  
  [request setPredicate:[NSPredicate predicateWithFormat:@"name == %@", 
                         @"default1"]];
  
  NSError *error = nil;
  
  NSManagedObject *param = [[moc executeFetchRequest:request 
                                               error:&error] lastObject];
  if (error) {
    NSLog(@"%@:%s Error fetching param: %@", [self class], _cmd, error);
    return;
  }
  
  if (!param) {
    param = [NSEntityDescription insertNewObjectForEntityForName:@"Parameter"
                                          inManagedObjectContext:moc];
    [param setValue:@"default1" forKey:@"name"];
  }
  
  [param setValue:@"SomeValue" forKey:@"value"];
}
//END:BadWrite

@end
