//
//  TagsMigrationPolicy.m
//  Locations
//
//  Created by Eugene on 12/25/12.
//  Copyright (c) 2012 Eugene. All rights reserved.
//

#import "TagsMigrationPolicy.h"
#import "Tag.h"

@implementation TagsMigrationPolicy

- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance entityMapping:(NSEntityMapping *)mapping manager:(NSMigrationManager *)manager error:(NSError *__autoreleasing *)error {
    // make sure we're working with correct class
    if ([sInstance.entity.name isEqualToString:@"Event"]) {
        NSManagedObjectContext *destMOC = manager.destinationContext;
        
        // create the Tag objects from the tags string
        NSString *tagsString = [sInstance valueForKey:@"tags"];
        NSMutableArray *tagsForEntity = [NSMutableArray array];
        if (tagsString.length > 0) {
            NSArray *tags = [tagsString componentsSeparatedByString:@","];
            for (NSString *tag in tags) {
                NSString *trimmedTag = [tag stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                if (trimmedTag.length > 0) {
                    // don't duplicate tags!
                    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Tag"];
                    request.predicate = [NSPredicate predicateWithFormat:@"name LIKE %@", trimmedTag];
                    NSError *err = nil;
                    NSArray *retTags = [destMOC executeFetchRequest:request error:&err];
                    if (retTags.count == 0) {
                        NSManagedObject *newTag = [NSEntityDescription insertNewObjectForEntityForName:@"Tag" inManagedObjectContext:destMOC];
                        [newTag setValue:trimmedTag forKey:@"name"];
                        [tagsForEntity addObject:newTag];
                    } else {
                        if (retTags.count > 1) {
                            NSLog(@"Warning. Found %d tags with name %@", retTags.count, trimmedTag);
                        }
                        [tagsForEntity addObjectsFromArray:retTags];
                    }
                }
            }
        }
        
        // create the destination Event object
        NSManagedObject *dst = [NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:destMOC];
        NSArray *keys = sInstance.entity.attributesByName.allKeys;
        NSMutableDictionary *values = [[sInstance dictionaryWithValuesForKeys:keys] mutableCopy];
        // resave tags as objects
        [values setValue:nil forKey:@"tags"];
        [tagsForEntity enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            Tag *tag = obj;
            [tag addEventsObject:(Event *)dst];
        }];
        [dst setValuesForKeysWithDictionary:[values copy]];
        [manager associateSourceInstance:sInstance withDestinationInstance:dst forEntityMapping:mapping];
        return YES;
    } else {
        NSLog(@"Unexpected source class: %@", sInstance.entity.name);
        return [super createDestinationInstancesForSourceInstance:sInstance entityMapping:mapping manager:manager error:error];
    }
}

@end
