/* Copyright (c) 2011 Artjom Popov */

#import "NSArray+Additions.h"

@implementation NSArray(Additions)

@dynamic urlEncodedValue;

- (NSString *)urlEncodedValue
{
	return [self urlEncodedValueByAppendingAfterString:nil];
}

- (id)firstObject
{
	return (self.count > 0) ? [self objectAtIndex:0] : nil;
}

- (NSString *)urlEncodedValueByAppendingAfterString:(NSString *)str
{
	NSMutableString *result = [NSMutableString string];
	Class class = [NSString class];
	char ch = 0x0;
	
	if(str) {
		[result appendString:str];
		
		if(![result hasSuffix:@"?"]) {
			[result appendString:@"?"];
		}
	}
	
	for(NSObject *child in self) {
		NSString *parameter = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, ([child isKindOfClass:class]) ? (CFStringRef)child : (CFStringRef)[child description], NULL, CFSTR("+=&"), kCFStringEncodingUTF8);
		
		if(ch) [result appendFormat:@"%c", ch];
		[result appendString:parameter];
		[parameter release];
		
		ch = (ch == '=') ? '&' : '=';
	}
	
	return result;
}

@end
