//
//  MPT_Timing.m
//  AUCoderDemo
//
//  Created by Andrew Salamon on 12/4/09.
//  Copyright 2009 Machine Perception Laboratory, University of California San Diego.. All rights reserved.
//

#import "MPT_Timing.h"
#import "MPT_Pair.h"

@implementation MPT_Timing
+ (void)test
{
	MPT_Timing *tester = [[MPT_Timing alloc] init];
	[tester stampWithID:@"First time stamp"];
	[tester stampWithID:@"Second time stamp"];
	[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
	[tester stampWithID:@"Third time stamp"];
	[tester stampWithID:@"Last time stamp"];
	NSLog( @"%@", [tester desc] );
	[tester release];
}

+ (MPT_Timing *)defaultTimer
{
	static MPT_Timing *timer = nil;
	if( nil == timer )
		timer = [[MPT_Timing alloc] init];
	return timer;
}

- (id)init
{
	self = [super init];
	
	lock = [[NSLock alloc] init];
	data = [[NSMutableArray alloc] init];
	counter = 1;
	formatter = [[NSDateFormatter alloc] initWithDateFormat:@"%H:%M:%S.%F" allowNaturalLanguage:NO];

	return self;
}

- (void)dealloc
{
	[lock lock];
	[data release];
	[lock unlock];
	[lock release];
	[formatter release];
	[super dealloc];
}

-(void)clear
{
	[lock lock];
	[data removeAllObjects];
	[lock unlock];
}

// Any access to data needs a lock since it might be called from multiple threads
-(void)stampWithID:(NSString *)stamp
{
//	[data setObject:[MPT_Pair pairWith:stamp and:[NSDate date]] forKey:[NSNumber numberWithInt:counter++]];
	MPT_Pair *pair = [MPT_Pair pairWith:stamp and:[NSDate date]];
	[lock lock];
	[data addObject:pair];
	[lock unlock];
}

-(NSString *)desc
{
	NSDate *first = nil;
	NSDate *prev = nil;
	NSMutableString *res = [NSMutableString string];
//	NSArray *sortedKeys = [[data allKeys] sortedArrayUsingSelector:@selector(compare:)];
	NSEnumerator *keyEnum = [data objectEnumerator];
	MPT_Pair *stamp;
	while( stamp = [keyEnum nextObject] )
	{
		// label, date/time, time since last stamp
		NSTimeInterval diff = 0.0;
		NSDate *cur = [stamp second];
		if( prev )
			diff = [cur timeIntervalSinceDate:prev];
		
		[res appendFormat:@"%@\t%@\t%f\n", [stamp first], [formatter stringFromDate:cur], diff];
		prev = cur;
		if( !first )
			first = cur;
	}
	[res appendFormat:@"Total time\t\t%f\n", [prev timeIntervalSinceDate:first]];
	[res appendString:@"\n"];
	return res;
}
@end
