#include "AdunKernel/AdunMultithreadedNonbondedTerm.h"

/**
Contains methods that can be executed on the threaded
object without having to send them to the thread itself
*/
@interface AdNonbondedTerm (MultithreadingExtensions)
/**
Starts a runloop - used to spawn the threaded object
*/
- (void) runThreadedLoop: (id) obj;
/**
Tells the threaded object it will recieve a calculation request
*/
- (void) shouldBeginCalculation;
/**
Asks the threaded object if it has finished a calculation
*/
- (BOOL) hasFinished;
/**
Terminates the thread
*/
- (void) endThreadedLoop;
/**
Tells the threaded object to prepare for another calculation.
*/
- (void) reset;
@end

/**
Each nonbonded term will have to have a special 
implementation of this method
*/
@interface AdNonbondedTerm (ThreadedCopy)
/**
Returns a copy of the nonbonded term that can be used
with AdMultithreadedNonbondedTerm.
*/
- (id) threadCopy;
@end

@implementation AdMultithreadedNonbondedTerm

- (NSArray*) _dividePairs: (id) pairs
{
	int i;
	NSMutableArray* array1, *array2;

	array1 = [NSMutableArray array];
	array2 = [NSMutableArray array];

	for(i=0; i<(int)[pairs count];i++)
	{
		if(i%2 == 0)
		{
			[array1 addObject: [pairs objectAtIndex: i]];
			[array2 addObject: [NSIndexSet indexSet]];
		}	
		else	
		{
			[array1 addObject: [NSIndexSet indexSet]];
			[array2 addObject: [pairs objectAtIndex: i]];
		}	
	}

	return [NSArray arrayWithObjects: array1, array2, nil];
}

- (id) initWithDictionary: (NSDictionary*) dict
{
	return [self initWithTerm: [dict objectForKey: @"term"]];
}

- (id) initWithTerm: (AdNonbondedTerm*) nonbondedTerm
{
	if((self = [super init]))
	{
		mainThread = [nonbondedTerm retain];
		threadedObj = [nonbondedTerm threadCopy];
		dividedPairs = [self _dividePairs: [mainThread nonbondedPairs]];
		[dividedPairs retain];
		[mainThread setNonbondedPairs: [dividedPairs objectAtIndex: 0]];
		[threadedObj setNonbondedPairs: [dividedPairs objectAtIndex: 1]];
		[NSThread detachNewThreadSelector: @selector(runThreadedLoop:)
			toTarget: threadedObj
			withObject: nil];
	}

	return self;
}

- (void) dealloc
{
	[threadedObj endThreadedLoop];
	[dividedPairs release];
	[mainThread release];
	[threadedObj release];
	[super dealloc];
}

- (void) evaluateEnergy
{
	//The threaded obj will only calculated forces
	/*[threadedObj shouldBeginCalculation];
	[mainThread evaluateEnergy];
	while(![threadedObj hasFinished])
		continue;
	
	[threadedObj reset];*/

	[mainThread evaluateEnergy];
}

- (void) evaluateForces
{
	int i,j;
	AdMatrix* forces1, *forces2;

	[threadedObj clearForces];
	[mainThread clearForces];

	[threadedObj shouldBeginCalculation];
	[mainThread evaluateForces];
	while(![threadedObj hasFinished])
		continue;

	[threadedObj reset];

	forces1 = [mainThread forces];
	forces2 = [threadedObj forces];
	for(i=0; i<forces->no_rows; i++)
		for(j=0; j<3; j++)
			forces->matrix[i][j] += (forces2->matrix[i][j] + forces1->matrix[i][j]);
}

- (void) setExternalForceMatrix: (AdMatrix*) matrix
{
	forces = matrix;
}

- (double) electrostaticEnergy;
{
	return [mainThread electrostaticEnergy] + [threadedObj electrostaticEnergy];
}	

- (double) lennardJonesEnergy;
{
	return [mainThread lennardJonesEnergy] + [threadedObj lennardJonesEnergy];
}

- (id) system
{
	return [mainThread system];
}

- (NSString*) lennardJonesType
{
	return [mainThread lennardJonesType];
}

@end

@implementation AdNonbondedTerm (MultithreadingExtensions)

/**
This is the method that run in the subthread. We communicate with
the subthread thRunLooprough the objects shared instance variables.
The subthread monitors the values of beginThreadedCalculation and
threadFinished and endThread which are set from the main thread.
*/
- (void) runThreadedLoop: (id) obj
{
	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	
	endThread = NO;
	beginThreadedCalculation = NO;
	threadFinished = NO;
	while(!endThread)
	{
		//Polling is bad but this is just a test.
		if(beginThreadedCalculation)
		{
			threadFinished = NO;
			NSDebugLLog(@"Multithread", @"Thread evaluating forces");
			[self evaluateForces];
			NSDebugLLog(@"Multithread", @"Complete");
			threadFinished = YES;
			beginThreadedCalculation = NO;
		}
	}

	[pool release];
	[NSThread exit];
}
/**
Tells the threaded object it will recieve a calculation request.
Executed on the main thread
*/
- (void) shouldBeginCalculation
{
	beginThreadedCalculation = YES;
}
/**
Asks the threaded object if it has finished
Executed on the main thread
*/
- (BOOL) hasFinished
{
	return threadFinished; 
}

- (void) reset
{
	threadFinished = NO;
}
/**
Terminates the thread
Executed on the main thread
*/
- (void) endThreadedLoop
{
	endThread = YES;
}

@end

@implementation AdPureNonbondedTerm (ThreadedCopy)

- (id) threadCopy
{
	return [[[self class] alloc]
		initWithSystem: system
		cutoff: cutoff
		updateInterval: updateInterval
		permittivity: permittivity
		nonbondedPairs: nil
		externalForceMatrix: NULL
		listHandlerClass: listHandlerClass];
}

@end
