//
//  MetadataItemTransformer.m
//  SimpleSearchApp
//
//  Created by ub on 25.07.09.
//  Copyright 2009 Udo Borkowski. All rights reserved.
//

#import "MetadataItemTransformer.h"


@implementation MetadataItemTransformer

+ (Class)transformedValueClass {
    return [NSString class];
}

+ (NSString*)valueStringForValue:(id)value {
	NSString* result;
	if (value == nil) {
		result = @"nil";
	} else if ([value isKindOfClass:[NSString class]]) {
		// FIXME: A more complete solution would escape some chars
		result = [NSString stringWithFormat:@"\"%@\"", value];
	} else {
		result = [NSString stringWithFormat:@"%@", value];
	}
	return result;
}

+ (NSString*)stringForAttribute:(NSString*)attribute of:item{
	id value = [item valueForAttribute:attribute];
	NSString* s = [MetadataItemTransformer valueStringForValue: value];
	return [NSString stringWithFormat:@"%@ = %@", attribute, s];
}

- (id)transformedValue:(id)value {
    if (value == nil) {
		return nil;
    }
	
    if (![value isKindOfClass:[NSArray class]]) {
        [NSException raise:NSInvalidArgumentException 
					format:@"NSArray of NSMetadataItem objects expected. Got %@",[value className]];
        return nil;
    }
	NSArray* array = (NSArray*)value;
	
	NSMutableString* s = [NSMutableString string];
	for (id item in array) {
		if (![item isMemberOfClass:[NSMetadataItem class]]) {
			[NSException raise:NSInvalidArgumentException 
						format:@"NSArray of NSMetadataItem objects expected. Array contained %@",[item className]];
			return nil;
		}
		
		NSMetadataItem* mdi = (NSMetadataItem*)item;
		
		// The "kMDItemPath" attribute name is not included in the attributes 
		// so add this "keyAndValue" explicitly.
		[s appendFormat: [MetadataItemTransformer stringForAttribute: @"kMDItemPath" of:mdi]];
		
		// add all remaining attributes, each starting at a new line
		for (NSString* key in [mdi attributes]) {
			[s appendFormat:@"\n%@", [MetadataItemTransformer stringForAttribute:key of:mdi]];
		}
		[s appendFormat:@"\n"];
	}
	return s;
}

@end
