#import "PPRecipe.h"

#import "AppDelegate.h"

NSString *kPPImagePath = @"kPPImagePath";
NSString *kPPObjectID = @"kPPObjectID";
NSString *kPPServes = @"kPPServes";

@implementation PPRecipe

@dynamic desc, name, type, author, lastUsed;

//START:metadataMethod
- (NSDictionary*)metadata;
{
  NSMutableDictionary *metadataDict = [NSMutableDictionary dictionary];
  
  [metadataDict setValue:[self name] 
                  forKey:(id)kMDItemTitle];
  [metadataDict setValue:[self desc] 
                  forKey:(id)kMDItemTextContent];
  [metadataDict setValue:[[self author] valueForKey:@"name"] 
                  forKey:(id)kMDItemAuthors];
  [metadataDict setValue:[self valueForKey:@"imagePath"] 
                  forKey:kPPImagePath];
  [metadataDict setValue:[self lastUsed] forKey:(id)kMDItemLastUsedDate];
  [metadataDict setValue:[self valueForKey:@"serves"] forKey:kPPServes];
  [metadataDict setValue:[NSString stringWithFormat:@"Recipe: %@", [self name]] 
                  forKey:(id)kMDItemDisplayName];
  [metadataDict setValue:[[[self objectID] URIRepresentation] absoluteString] 
                  forKey:kPPObjectID];
  return metadataDict;
}
//END:metadataMethod

//START:metadataNameMethod
- (NSString*)metadataFilename;
{
  return [[self name] stringByAppendingPathExtension:@"grokkingrecipe"];
}
//END:metadataNameMethod

//START:imagmMethodsForSyncing
- (NSData*)image
{
  NSLog(@"%@:%s entered", [self class], _cmd);
  if (image) return image;
  NSString *path = [self primitiveValueForKey:@"imagePath"];
  if (!path) return nil;
  image = [[NSData alloc] initWithContentsOfFile:path];
  return image;
}

- (void)setImage:(NSData*)data
{
  NSLog(@"%@:%s entered", [self class], _cmd);
  NSString *destPath = [self primitiveValueForKey:@"imagePath"];
  if (!destPath) {
    //Build the path we want the file to be at
    destPath = [[NSApp delegate] applicationSupportFolder];
    NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString];
    destPath = [destPath stringByAppendingPathComponent:guid];
    [self setValue:destPath forKey:@"imagePath"];
  }
  [data writeToFile:destPath atomically:NO];
  [data retain];
  [image release];
  image = data;
}
//END:imagmMethodsForSyncing

- (void)willTurnIntoFault
{
  [image release], image = nil;
}

@end
