//
//  GTRunLoopTimer.mm
//  All
//
//  Created by nhn on 11. 1. 1..
//  Copyright 2011 nhn KEH. All rights reserved.
//

#import "GTRunLoopTimer.h"

static void RunLoopTimerCallback(CFRunLoopTimerRef timer, void *info);


@implementation GTRunLoopTimer

@synthesize userInfo;

- (id)initWithDelegate:(id)aDelegate withInterval:(int)msec withParam:(id)aUserInfo
{
	self = [super init];
	
	double interval = msec / 1000.;

	CFAbsoluteTime fireDate = CFAbsoluteTimeGetCurrent() + interval;
	
	CFRunLoopTimerContext context = {0, self, NULL, NULL, NULL};
	
	delegate = aDelegate;
	userInfo = aUserInfo;
		
	if ([delegate respondsToSelector:@selector(onGTRunLoop_RegisterTimer:)])
		[delegate onGTRunLoop_RegisterTimer:self];
	
	runLoopTimer = CFRunLoopTimerCreate(kCFAllocatorDefault, 
										  fireDate, 
										  interval, 
										  0, 
										  0, 
										  &RunLoopTimerCallback, 
										  &context);
		
	notifyInvalidateFlag = NO;
	
	return self;
}


- (void)dealloc
{
	[self invaldate];
	
	CFRelease(runLoopTimer);
	
	if(userInfo)
	{
		if ( [userInfo isKindOfClass:[NSObject class]] )
			[userInfo release];
	}
	
	[super dealloc];
}


- (void)invaldate
{
	CFRunLoopTimerInvalidate(runLoopTimer);

	if(NO == notifyInvalidateFlag)
	{
		notifyInvalidateFlag = YES;
		
		if ([delegate respondsToSelector:@selector(onGTRunLoop_RemoveTimer:)])
			[delegate onGTRunLoop_RemoveTimer:self];
	}
}


- (void)addToRunLoop:(CFRunLoopRef)aRunLoop
{
	runLoop = aRunLoop;
	
	CFRunLoopAddTimer(runLoop, runLoopTimer, kCFRunLoopDefaultMode);
}


- (void)addToCurrentRunLoop
{
	CFRunLoopRef aRunLoop = CFRunLoopGetCurrent();
	[self addToRunLoop:aRunLoop];
}


- (void)addToMainRunLoop
{
	CFRunLoopRef aRunLoop = CFRunLoopGetMain();
	[self addToRunLoop:aRunLoop];
}

- (void)timerFired
{
	if ([delegate respondsToSelector:@selector(onGTRunLoop_TimerFired:)])
		[delegate onGTRunLoop_TimerFired:self];
}

@end
///////////////////////////////////////////////////////////////////////////////////////////


static void RunLoopTimerCallback(CFRunLoopTimerRef timer, void *info)
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	GTRunLoopTimer* obj = [[(GTRunLoopTimer*)info retain] autorelease];
	
	[obj timerFired];
	
	[pool release];	
}




