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

#import "NSStringOgreKit.h"
#import <OgreKit/OgreKit.h>

@implementation NSString (NSStringOgreKit)

APPKIT_EXTERN NSThread* TheMainThread;

- (NSString *)replaceWithExpression:(NSString *)exp
							replace:(NSString *)replace
{
	return [self replaceWithExpression:exp replace:replace options:OgreNoneOption];
}

- (NSString *)replaceWithExpression:(NSString *)exp
							replace:(NSString *)replace
							options:(unsigned)options
{
	NSMutableString *string = nil;
	@try
	{
#if defined(_D_E_B_U_G_)
		if ([[NSThread currentThread] isEqual:TheMainThread])
		{
			LOG(@"[%@ replaceWithExpression] MAIN THREAD !!!", [self className]);
		}
#endif //defined(_D_E_B_U_G_)
		@synchronized([NSApplication sharedApplication])
		{
			string = [NSMutableString stringWithString:self];
			[string replaceOccurrencesOfRegularExpressionString:exp
													 withString:replace
														options:options
														  range:NSMakeRange(0, [self length])];
		}
	}
	@catch (NSException *exception)
	{
		EXPLOG(@"[%@ replaceWithExpression] EXCEPTION\n%@: %@", [self className], [exception name], [exception reason]);
	}
	return string;
}

- (int)lengthOfRegularExpression:(NSString *)regExp
{
	return [self lengthOfRegularExpression:regExp withOptions:OgreNoneOption];
}

- (int)lengthOfRegularExpression:(NSString *)regExp
						 withOptions:(unsigned)options
{
	int length = 0;
	@try
	{
#if defined(_D_E_B_U_G_)
		if ([[NSThread currentThread] isEqual:TheMainThread])
		{
			LOG(@"[%@ lengthOfRegularExpression] MAIN THREAD !!!", [self className]);
		}
#endif //defined(_D_E_B_U_G_)
		@synchronized([NSApplication sharedApplication])
		{
			length = [self rangeOfRegularExpressionString:regExp options:options].length;
		}
	}
	@catch (NSException *exception)
	{
		EXPLOG(@"[%@ lengthOfRegularExpression] EXCEPTION\n%@\n%@: %@", [self className], regExp, [exception name], [exception reason]);
	}
	return length;
}


- (NSString *)regularizeString
{
	NSString *regStr = nil;
	@try
	{
#if defined(_D_E_B_U_G_)
		if ([[NSThread currentThread] isEqual:TheMainThread])
		{
			LOG(@"[%@ regularizeString] MAIN THREAD !!!", [self className]);
		}
#endif //defined(_D_E_B_U_G_)
		@synchronized([NSApplication sharedApplication])
		{
			regStr = [OGRegularExpression regularizeString:self];
		}
	}
	@catch (NSException *exception)
	{
		EXPLOG(@"[%@ regularizeString] EXCEPTION\n%@: %@", [self className], [exception name], [exception reason]);
	}
	return regStr;
}

@end
