
/*
	Output a dictionary suitable for attaching to an HTTP request
	Original Source: <http://cocoa.karelia.com/Foundation_Categories/NSDictionary/Output_a_dictionary.m>
	(See copyright notice at <http://cocoa.karelia.com>)
*/

/*"	This category adds methods for dealing with HTTP input and output to an NSDictionary.  This actually appears as part of the CURLHandle package so strictly speaking, it's in the public domain.
"*/

/*"	Convert a dictionary to an HTTP-formatted string with 7-bit ASCII encoding;
	see formatForHTTPUsingEncoding.
"*/

- (NSString *) formatForHTTP
{
	return [self formatForHTTPUsingEncoding:NSASCIIStringEncoding];
		// default to dumb ASCII only
}

/*"	Convert a dictionary to an HTTP-formatted string with the given encoding.
	Spaces are turned into +; other special characters are escaped with %;
	keys and values are output as key=value; in between arguments is &.
"*/

- (NSString *) formatForHTTPUsingEncoding:(NSStringEncoding)inEncoding
{
	return [self formatForHTTPUsingEncoding:inEncoding ordering:nil];
}

/*"	Convert a dictionary to an HTTP-formatted string with the given encoding, as above.  The inOrdering parameter specifies the order to place the inputs, for servers that care about this.  (Note that keys in the dictionary that aren't in inOrdering will not be included.)  If inOrdering is nil, all keys and values will be output in an unspecified order.
"*/

- (NSString *) formatForHTTPUsingEncoding:(NSStringEncoding)inEncoding ordering:(NSArray *)inOrdering
{
	NSMutableString *s = [NSMutableString stringWithCapacity:256];
	NSEnumerator *e = (nil == inOrdering) ? [self keyEnumerator] : [inOrdering objectEnumerator];
	id key;
	CFStringEncoding cfStrEnc = CFStringConvertNSStringEncodingToEncoding(inEncoding);

	while ((key = [e nextObject]))
	{
		NSString *escapedKey
		= [(NSString *) CFURLCreateStringByAddingPercentEscapes(
														 NULL, (CFStringRef) key, NULL, NULL, cfStrEnc) autorelease];
		NSString *escapedObject
			= [(NSString *) CFURLCreateStringByAddingPercentEscapes(
														  NULL, (CFStringRef) [[self objectForKey:key] description], NULL, NULL, cfStrEnc) autorelease];
		[s appendFormat:@"%@=%@&", escapedKey, escapedObject];
	}
	// Delete final & from the string
	if (![s isEqualToString:@""])
	{
		[s deleteCharactersInRange:NSMakeRange([s length]-1, 1)];
	}
	return s;	
}