
#import "ShipBuilder.h"
#import "OriginalView.h"
#import "OutputView.h"
#import "Scale.h"

@implementation ShipBuilder

- showInfoPanel:sender
{
	if (!infoPanel)
		[NXApp loadNibSection:"Info.nib" owner:self withNames:NO];
	
	[[infoPanel center] makeKeyAndOrderFront:self];
	return self;
}

- (BOOL)realityCheck
{
	if (inProgress)
		return NO;
	
	if (![originalView imageLoaded]) {
		NXRunLocalizedAlertPanel (NULL, NULL,
			"Please open an image file.",
			NULL, NULL, NULL);
		return NO;
	}
	
	if ([framesField intValue] <= 0) {
		NXRunLocalizedAlertPanel (NULL, NULL,
			"Please enter a positive number of images to create.",
			NULL, NULL, NULL);
		return NO;
	}
	
	if ([outputSizeField intValue] < 3) {
		NXRunLocalizedAlertPanel (NULL, NULL,
			"Please enter an output size of at least three pixels.",
			NULL, NULL, NULL);
		return NO;
	}
	
	return YES;
}

- endCompute
{
	[openMenuItem setEnabled:YES];
	[computeButton setState:0];
	inProgress = NO;
	return self;
}

- compute:sender
{
	int numFrames, frameSize;

	if (![self realityCheck]) {
		[self endCompute];
		return nil;
	}
	
	inProgress = YES;
	[openMenuItem setEnabled:NO];
	numFrames = [framesField intValue];
	frameSize = [outputSizeField intValue];
	
	[[outputView window] makeKeyAndOrderFront:self];
	[outputView beginSeriesOfFrames:numFrames withSize:frameSize];
	[self perform:@selector (doNextFrame:) with:self
		afterDelay:100 cancelPrevious:NO];
	
    return self;
}

- doNextFrame:sender
{
	float degrees;
	
	if ([outputView seriesComplete] || !inProgress) {
		[self endCompute];
		return nil;
	}
	
	degrees = (float)[outputView nextFrame] / (float)[outputView numFrames];
	degrees *= 360.;
	
	[[originalView setRotationInDegrees:degrees] display];
	NXPing ();
	
	[[outputView addFrame:[scaleFilter filter:[originalView bitmap]]] display];
	NXPing ();
	
	[self perform:@selector (doNextFrame:) with:self
		afterDelay:100 cancelPrevious:NO];
	
	return self;
}

@end
