//
//  ServiceChuitter.m
//  Afficheur
//
//  Created by kichi on 09/09/26.
//  Copyright 2009 Katsuhiko Ichinose. All rights reserved.
//

#import "ServiceChuitter.h"
#import "AfficheurController.h"
#import "AfficheurGrowl.h"
#import "AfficheurPreferences.h"
#import "HTTP.h"
#import "TinyURL.h"
#import "ServiceXMPP.h"
#import "NSStringOgreKit.h"
#import <OgreKit/OgreKit.h>


@implementation ServiceChuitter

- (id)init:(NSString *)service
WithController:(AfficheurController *)controller
preferences:(AfficheurPreferences *)preferences
{
	self = [super init:service
		WithController:controller
		   preferences:preferences];
	if (self)
	{
		_notifyGroup = GrowlAfficheurChuitterGroupNotify;
	}
	return self;
}

- (void)setupXMPP:(ServiceXMPP *)xmpp
{
	[xmpp addService:Chuitter withObject:self];
	if (NO && [_preferences accountChuitterUseXMPP])
	{
		[xmpp addXMPP:Chuitter
			  withJid:[_preferences accountChuitterJidXMPP]
				 pass:[_preferences accountChuitterPassXMPP]
			   server:[_preferences accountChuitterServerXMPP]
				 port:[_preferences accountChuitterPortXMPP]
			  offline:[_preferences accountChuitterOfflineXMPP]];
	}
	else
	{
		[xmpp removeXMPP:Chuitter];
	}
}

- (BOOL)checkRetrieveTimeline:(NSDate *)now
{
	BOOL check = NO;
	@synchronized(self)
	{
		check = [self checkRetrieve:now
						   withDate:_dateTimeline
						   interval:[_preferences accountChuitterIntervalTimeline]];
	}
	return check;
}

- (BOOL)checkRetrieveReplies:(NSDate *)now
{
	BOOL check = NO;
	@synchronized(self)
	{
		check =  [self checkRetrieve:now
							withDate:_dateReplies
							interval:[_preferences accountChuitterIntervalReplies]];
	}
	return check;
}

- (BOOL)checkRetrieveDM:(NSDate *)now
{
	BOOL check = NO;
	@synchronized(self)
	{
		check = [self checkRetrieve:now
						   withDate:_dateDM
						   interval:[_preferences accountChuitterIntervalDM]];
	}
	return check;
}

- (NSDictionary *)apiParam
{
	NSString *user = [_preferences accountChuitterUser];
	NSString *pass = [_preferences accountChuitterPass];
	return [NSDictionary dictionaryWithObjectsAndKeys:
			@"chuitter.jp", TwitterHost,
			@"http://chuitter.jp/api", TwitterURL,
			user, TwitterUser,
			pass, TwitterPass,
			Afficheur, TwitterSource,
			nil];
}

- (void)post:(NSString *)status
   withReply:(NSString *)reply
{
	//@synchronized(self)
	{
		@try
		{
			if (![reply isEqualToString:@""])
			{
				reply = [NSString stringWithFormat:@"&in_reply_to_status_id=%@", reply];
			}
			NSDictionary *dic = [self apiParam];
			if ([_preferences generalConvertEmoji])
			{
				status = [self stringFromEmoji:status];
			}
			@synchronized([NSApplication sharedApplication])
			{
				@try
				{
					NSString *exp = [NSString stringWithFormat:@"%@", [AfficheurController stringRegularExpressionURL]];
					OGRegularExpression *regex = [OGRegularExpression
												  regularExpressionWithString:exp
												  options:OgreMultilineOption];
					status = [regex replaceAllMatchesInString:status
													 delegate:self
											  replaceSelector:@selector(extractShortenURL:contextInfo:)
												  contextInfo:nil];
					NSString *text = [NSString stringWithFormat:@"%@", status];
					while ([text lengthOfRegularExpression:[AfficheurController stringRegularExpressionURL]
											   withOptions:OgreMultilineOption])
					{
						NSString *url = [text replaceWithExpression:[NSString stringWithFormat:@"^.*?(%@).*$",
																	 [AfficheurController stringRegularExpressionURL]]
															replace:@"\\1"
															options:OgreMultilineOption];
						NSString *tiny = [TinyURL createJmp:url
												  withLogin:BitLyLogin
													 apiKey:BitLyApiKey];
						LOG(@"[%@(%@) post]\n%@\n%@", [self className], _service, url, tiny);
						tiny = [tiny replaceWithExpression:@"(?:http|https)://" replace:@""];
						status = [status replaceWithExpression:[url regularizeString]
													   replace:tiny
													   options:OgreMultilineOption];
						text = [text replaceWithExpression:[url regularizeString]
												   replace:@""
												   options:OgreMultilineOption];
					}
					LOG(@"[%@(%@) post]\n%@", [self className], _service, status);
				}
				@catch (NSException *exception)
				{
					EXPLOG(@"[%@(%@) post] EXCEPTION\n%@: %@", [self className], _service, [exception name], [exception reason]);
				}
			}
			[self performPost:[[NSArray alloc] initWithObjects:status, dic, reply, nil]];
		}
		@catch (NSException *exception)
		{
			EXPLOG(@"[%@(%@) post] EXCEPTION\n%@: %@", [self className], _service, [exception name], [exception reason]);
		}
	}
}

- (NSDictionary *)parse:(NSDictionary *)obj
			   withUser:(NSString *)user_id
				   kind:(int)kind
				  first:(BOOL)first
{
	obj = [super parse:obj
			  withUser:user_id
				  kind:kind
				 first:first];
	if (obj)
	{
		NSMutableDictionary *item = [NSMutableDictionary dictionaryWithDictionary:obj];
		NSString *userProfile = [item valueForKey:KeyUserProfile];
		userProfile = [userProfile replaceWithExpression:@"tweeter\\.jp\\/chuitter"
												 replace:@"chuitter.jp"];
	//	EXPLOG(@"[%@(%@) parse]\n%@", [self className], _service, userProfile);
		[item setObject:userProfile forKey:KeyUserProfile];
		obj = item;
	}
	return obj;
}

- (void)permalink:(NSString *)item_id
{
	@try
	{
		id item = [self fetchALL:item_id withService:_service];
		if (item)
		{
			if ([[item valueForKey:KeyKind] isEqualToString:KindDM])
			{
				NSString *user = [_preferences accountChuitterUser];
				[self doOpenURL:[NSString stringWithFormat:@"http://tweeter.jp/chuitter/%@/inbox", user]];
			}
			else
			{
				[self doOpenURL:[NSString stringWithFormat:@"http://tweeter.jp/chuitter/notice/%@", item_id]];
			}
		}
	}
	@catch (NSException *exception)
	{
		EXPLOG(@"[%@(%@) permalink] EXCEPTION\n%@: %@", [self className], _service, [exception name], [exception reason]);
	}
}

@end
