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

#import "TumblrAPI.h"
#import <JSON/JSON.h>
#import <OgreKit/OgreKit.h>

@implementation TumblrAPI

- (id)postWithAuth:(NSString *)path
			header:(NSMutableDictionary *)header
			  body:(NSString *)body
{
	NSString *generator = @"";
	if ([_dic valueForKey:TwitterSource])
	{
		generator = [NSString stringWithFormat:@"&generator=%@", [_dic valueForKey:TwitterSource]];
	}
	NSString *auth = [HTTP base64String:
					  [NSString stringWithFormat:@"%@:%@",
					   [_dic valueForKey:TwitterUser],
					   [_dic valueForKey:TwitterPass]]];
	[header setValue:[_dic valueForKey:TwitterHost] forKey:@"Host"];
	[header setValue:[NSString stringWithFormat:@"Basic %@", auth] forKey:@"Authorization"];
	return [self post:[NSString stringWithFormat:@"%@%@", [_dic valueForKey:TwitterURL], path]
			   header:header
				 body:[NSString stringWithFormat:@"email=%@&password=%@&%@%@",
					   [HTTP urlEncode:[_dic valueForKey:TwitterUser]
							 unescaped:nil
							   escaped:@"+"],
					   [HTTP urlEncode:[_dic valueForKey:TwitterPass]
							 unescaped:nil
							   escaped:@"+"],
					   body,
					   generator]];
}

- (id)createLink:(NSString *)link
		   title:(NSString *)title
{
	NSString *name = @"";
	if (title && ![title isEqualToString:@""])
	{
			name = [NSString stringWithFormat:@"&name=%@", [HTTP urlEncode:title
																 unescaped:nil
																   escaped:@"+"]];
	}
	id result = [self postWithAuth:@"/api/write"
							header:[NSMutableDictionary dictionaryWithObjectsAndKeys:
									@"application/x-www-form-urlencoded",
									@"Content-Type",
									nil]
							  body:[NSString stringWithFormat:@"type=link&url=%@%@",
									[HTTP urlEncode:link
										  unescaped:nil
											escaped:@"+"],
									name]];
	return [self determineError:result WithJSON:NO];
}

@end
