/*
	simpleZillionJob.m
	Mon Dec  9 18:55:08 CET 2002
 */

#import "simpleZillionJob.h"
#include <math.h>

#define SIMPLE_JOBS_COUNT	100

@interface SimpleJobEnumerator : NSEnumerator { int	number; }
@end
@implementation SimpleJobEnumerator
- initWithSeed:seed {
	if (!(self = [super init])) return self;
	number = seed? [(NSNumber *)seed intValue]: 0;
	return self;
}
- nextObject { NSLog(@"Enum number %d", number);
	return number < SIMPLE_JOBS_COUNT? [NSNumber numberWithInt:number++]: nil;
}
@end

@implementation SimpleZillionJob

- (NSString *)jobId { return @"simpleJob"; }
- (BOOL)storesOutcomesInMemory { return YES; }

- initWithBundle:(NSBundle *)someBundle
	resources:(NSData *)resources
	jobHandler:(id <ZillionJobHandler>)jobHandler
{
	if (! (self = [super init])) return self;
	handler = [jobHandler retain];
	return self;
}

- (void)dealloc
{
	[handler release];
	[super dealloc];
}

- (NSEnumerator *)seedEnumeratorWithSeed:(NSData *)dataSeed {
	id	seed = !dataSeed? nil: [NSUnarchiver unarchiveObjectWithData:dataSeed];
	return [[[SimpleJobEnumerator alloc] initWithSeed:seed] autorelease];
}
- (void)startJobUnitWithSeed:seed
{
#	if 0
		NSLog(@"sleeping");
		[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]];
#	else
		// do some real "numbercrunching"
#		define	ITERATIONS	10000ULL
		unsigned long long	i;
		double		outcome = 1;
		NSLog(@"lots of iterations");
		for (i = 0; i < ITERATIONS; i++) {
			outcome *= exp(i) * log(i) * sin(i) * cos(i);
		}
		[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
#	endif

	[handler submitOutcome:[NSArchiver archivedDataWithRootObject:
		[NSNumber numberWithInt:[(NSNumber *)seed intValue]*2]]
		ofJob:[self jobId] forSeed:seed storeHints:nil];
}

- (NSData *)dataRepresentationOfSeed:seed {
	return seed? [NSArchiver archivedDataWithRootObject:seed]: nil;
}
- seedObjectFromDataRepresentation:(NSData *)seed {
	return seed? [NSUnarchiver unarchiveObjectWithData:seed]: nil;
}

- (void)saveOutcome:(NSData *)outcome forSeedId:(NSData *)seedId
	storeHints:(NSDictionary *)someStoreHint
{
	NSLog(@"about to save outcome:%@", outcome);
	//[handler setOutcome:outcome forSeedId:seedId andJobId:[self jobId]];
}

- (void)sealJobOutcomes
{
	//NSLog(@"Sealing job to: %@", [aServer outcomeDictionaryForJobId:
	//	[[self class] jobIdWithResources:nil]]);
	NSLog(@"Did seal %@", [self jobId]);
}

@end
