#import "Fly.h"
#import "FlyCommon.h"
#import "FlyFuncs.h"

#import <stdio.h>

@implementation Fly

- init
{
	long	raw;

	[super init];
	head = random() % kMaxDir;
	raw = random() % kMaxSpeed;
	speed = (raw == 0) ? 1 : raw;
	firstState = YES;
	isSplat = NO;
	NXSetSize(&(cell.size), kFlyCellWidth, kFlyCellHeight);
	[self setCellRect];

	return self;
}

- free
{
	return [super free];
}

- setFlyImage:(NXImage *)image
{
	fly = image;
	return self;
}

- setGutsImage:(NXImage *)image
{
	guts = image;
	return self;
}

- setMaskImage:(NXImage *)image
{
	mask = image;
	return self;
}

- setSplatSnd:(Sound *)snd
{
	splat = snd;
	return self;
}

- setCellRect
{
	cell.origin.x = head * kFlyCellWidth;
	cell.origin.y = (firstState) ? kStateOffset : kStateBase;
	
	return self;
}

- setHeading:(long)h
{
	head = h;
	return self;
}

- setSpeedValue:(float)s
{
	speed = s;
	return self;
}

- setPeriod:(long)period
{
	statePeriod = period;
	return self;
}

- setPosition:(NXPoint)p
{
	pos = p;
	return self;
}

- setState:(BOOL)state
{
	firstState = state;
	return self;
}

- setNoTurn:(long)nt andLeftTurn:(long)lt
{
	noTurn = nt;
	leftTurn = lt;
	return self;
}

- toggleSplat:(BOOL)splatted
{
	isSplat = splatted;
	return self;
}

- (NXPoint *)position
{
	return(&pos);
}

- (long)heading
{
	return(head);
}
 
- (float)speed
{
	return(speed);
}

- (BOOL)isFirstState
{
	return(firstState);
}

- (long)statePeriod
{
	return(statePeriod);
}

- (long)noTurn
{
	return(noTurn);
}

- (long)leftTurn
{
	return(leftTurn);
}

- (BOOL)isSplat
{
	return(isSplat);
}

- doSplat
{
	[splat play];
	[self drawGuts];
	[self toggleSplat:YES];
	
	return self;
}

- drawFly
{
	[fly composite:NX_SOVER fromRect:&cell toPoint:&pos];
	return self;
}

- eraseFly
{
	[mask composite:NX_SOVER fromRect:&cell toPoint:&pos];
	return self;
}

- drawGuts
{
	gutsPos = pos;
	gutsPos.x -= (kGutsImageWidth - (kFlyCellWidth+1)) / 2 ;
	gutsPos.y -= (kGutsImageHeight - (kFlyCellHeight+1)) / 2;
	[guts composite:NX_SOVER toPoint:&gutsPos];

	return self;
}

- eraseGuts
{
	PSsetgray(kBackgroundGray);
	PSrectfill(gutsPos.x, gutsPos.y, kGutsImageWidth, kGutsImageHeight);

	return self;
}

@end
