//
//  TinyURL.m
//  Afficheur
//
//  Created by kichi on 08/04/10.
//  Copyright 2008 Katsuhiko Ichinose. All rights reserved.
//

#import "TinyURL.h"
#import "HTTP.h"
#import <JSON/JSON.h>
#import "NSStringOgreKit.h"
#import "AfficheurController.h"

@implementation TinyURL

static NSString *VERSION_BITLY = @"2.0.1";

+ (NSString *)create:(NSString *)url
{
	LOG(@"[%@ create]\n%@\n%@", [self className], url, [HTTP urlEncode:url unescaped:@"" escaped:@""]);
	NSString *path = [NSString stringWithFormat:
					  @"http://tinyurl.com/api-create.php?url=%@",
					  [HTTP urlEncode:url
							unescaped:@""
							  escaped:@""]];
	NSDictionary *header = [NSDictionary dictionaryWithObjectsAndKeys:
							@"tinyurl.com", @"Host",
							nil];
	HTTP *http = [[[HTTP alloc] init] autorelease];
	[http setTimeoutInterval:5];
	id result = [http get:path header:header body:@""];
	if (![result isKindOfClass:[NSData class]])
	{
		return nil;
	}
	NSString *tiny = [[[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding] autorelease];
	LOG(@"[%@ create]\n%@\n%@", [self className], url, tiny);
	return tiny;
}

+ (NSString *)createISgd:(NSString *)url
{
	LOG(@"[%@ createISgd]\n%@\n%@", [self className], url, [HTTP urlEncode:url unescaped:@"" escaped:@""]);
	NSString *path = [NSString stringWithFormat:
					  @"http://is.gd/api.php?longurl=%@",
					  [HTTP urlEncode:url
							unescaped:@""
							  escaped:@""]];
	NSDictionary *header = [NSDictionary dictionaryWithObjectsAndKeys:
							@"is.gd", @"Host",
							nil];
	HTTP *http = [[[HTTP alloc] init] autorelease];
	[http setTimeoutInterval:5];
	id result = [http get:path header:header body:@""];
	if (![result isKindOfClass:[NSData class]])
	{
		return nil;
	}
	NSString *tiny = [[[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding] autorelease];
	LOG(@"[%@ createISgd]\n%@\n%@", [self className], url, tiny);
	return tiny;
}

+ (NSString *)createBitLy:(NSString *)url
				 withHost:(NSString *)host
					login:(NSString *)login
				   apiKey:(NSString *)apiKey
{
	LOG(@"[%@ createBitLy]\n%@\n%@", [self className], url, [HTTP urlEncode:url unescaped:@"" escaped:@""]);
	if ([url lengthOfRegularExpression:stringURLShorten])
	{
		return url;
	}
	NSString *path = [NSString stringWithFormat:
					  @"http://%@/shorten?version=%@&longUrl=%@&login=%@&apiKey=%@",
					  host,
					  VERSION_BITLY,
					  [HTTP urlEncode:url
							unescaped:@""
							  escaped:@"?&+"],
					  login,
					  apiKey];
	NSDictionary *header = [NSDictionary dictionaryWithObjectsAndKeys:
							host, @"Host",
							nil];
	HTTP *http = [[[HTTP alloc] init] autorelease];
	[http setTimeoutInterval:5];
	id result = [http get:path header:header body:@""];
	if (![result isKindOfClass:[NSData class]])
	{
		return nil;
	}
	result = [[[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding] autorelease];
	@try
	{
		@synchronized([NSApplication sharedApplication])
		{
			result = [result JSONValue];
		}
	}
	@catch (NSException *exception)
	{
		EXPLOG(@"[%@ createBitLy] EXCEPTION\n%@: %@", [self className], [exception name], [exception reason]);
		result = nil;
	}
	@try
	{
		if (result && [result isKindOfClass:[NSDictionary class]])
		{
			LOG(@"[%@ createBitLy]\n%@\n%@", [self className], url, result);
			NSString *statusCode = [result valueForKey:@"statusCode"];
			NSDictionary *results = nil;
			NSArray *keys = nil;
			NSString *shortUrl = nil;
			if (statusCode && [statusCode isEqualToString:@"OK"])
			{
				results = [result valueForKey:@"results"];
			}
			if (results && [results isKindOfClass:[NSDictionary class]])
			{
				keys = [results allKeys];
			}
			if (keys && [keys isKindOfClass:[NSArray class]] && [keys count] > 0)
			{
				results = [results valueForKey:[keys objectAtIndex:0]];
			}
			else
			{
				results = nil;
			}
			if (results && [results isKindOfClass:[NSDictionary class]])
			{
				shortUrl = [results valueForKey:@"shortUrl"];
			}
			if (shortUrl && [shortUrl isKindOfClass:[NSString class]])
			{
				result = shortUrl;
			}
			else
			{
				result = nil;
			}
			
		}
	}
	@catch (NSException *exception)
	{
		EXPLOG(@"[%@ createBitLy] EXCEPTION\n%@: %@", [self className], [exception name], [exception reason]);
		result = nil;
	}
	LOG(@"[%@ createBitLy]\n%@\n%@", [self className], url, result);
	return result;
}

+ (NSString *)createBitLy:(NSString *)url
				withLogin:(NSString *)login
				   apiKey:(NSString *)apiKey
{
	return [TinyURL createBitLy:url
					   withHost:@"api.bit.ly"
						  login:login
						 apiKey:apiKey];
}

+ (NSString *)createJmp:(NSString *)url
			  withLogin:(NSString *)login
				 apiKey:(NSString *)apiKey
{
	return [TinyURL createBitLy:url
					   withHost:@"api.j.mp"
						  login:login
						 apiKey:apiKey];
}

+ (NSString *)expandBitLy:(NSString *)url
				 withHost:(NSString *)host
					login:(NSString *)login
				   apiKey:(NSString *)apiKey
{
	LOG(@"[%@ expandBitLy]\n%@\n%@", [self className], url, [HTTP urlEncode:url unescaped:@"" escaped:@""]);
	NSString *path = [NSString stringWithFormat:
					  @"http://%@/expand?version=%@&shortUrl=%@&login=%@&apiKey=%@",
					  host,
					  VERSION_BITLY,
					  [HTTP urlEncode:url
							unescaped:@""
							  escaped:@""],
					  login,
					  apiKey];
	NSDictionary *header = [NSDictionary dictionaryWithObjectsAndKeys:
							host, @"Host",
							nil];
	HTTP *http = [[[HTTP alloc] init] autorelease];
	[http setTimeoutInterval:5];
	id result = [http get:path header:header body:@""];
	if (![result isKindOfClass:[NSData class]])
	{
		return nil;
	}
	result = [[[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding] autorelease];
	@try
	{
		@synchronized([NSApplication sharedApplication])
		{
			result = [result JSONValue];
		}
	}
	@catch (NSException *exception)
	{
		EXPLOG(@"[%@ expandBitLy] EXCEPTION\n%@: %@", [self className], [exception name], [exception reason]);
		result = nil;
	}
	@try
	{
		if (result && [result isKindOfClass:[NSDictionary class]])
		{
			LOG(@"[%@ expandBitLy]\n%@\n%@", [self className], url, result);
			NSString *statusCode = [result valueForKey:@"statusCode"];
			NSDictionary *results = nil;
			NSArray *keys = nil;
			NSString *longUrl = nil;
			if (statusCode && [statusCode isEqualToString:@"OK"])
			{
				results = [result valueForKey:@"results"];
			}
			if (results && [results isKindOfClass:[NSDictionary class]])
			{
				keys = [results allKeys];
			}
			if (keys && [keys isKindOfClass:[NSArray class]] && [keys count] > 0)
			{
				results = [results valueForKey:[keys objectAtIndex:0]];
			}
			else
			{
				results = nil;
			}
			if (results && [results isKindOfClass:[NSDictionary class]])
			{
				longUrl = [results valueForKey:@"longUrl"];
			}
			if (longUrl && [longUrl isKindOfClass:[NSString class]])
			{
				result = longUrl;
			}
			else
			{
				result = nil;
			}
			
		}
	}
	@catch (NSException *exception)
	{
		EXPLOG(@"[%@ expandBitLy] EXCEPTION\n%@: %@", [self className], [exception name], [exception reason]);
		result = nil;
	}
	LOG(@"[%@ expandBitLy]\n%@\n%@", [self className], url, result);
	return result;
}

+ (NSString *)expandBitLy:(NSString *)url
				withLogin:(NSString *)login
				   apiKey:(NSString *)apiKey
{
	return [TinyURL expandBitLy:url
					   withHost:@"api.bit.ly"
						  login:login
						 apiKey:apiKey];
}

+ (NSString *)expandJmp:(NSString *)url
			  withLogin:(NSString *)login
				 apiKey:(NSString *)apiKey
{
	return [TinyURL expandBitLy:url
					   withHost:@"api.j.mp"
						  login:login
						 apiKey:apiKey];
}

@end
