
#import "FlyingWindow.h"

static id contentImage = nil;

@implementation EnhanceFlyingWindow

- initAt:(NXPoint *)thePoint
{ // set up window with image and put it on the screen centered at thePoint
	NXRect theFrame; NXPoint zeroPoint = { 0.0, 0.0 };
	if (!contentImage)
		contentImage = [NXImage findImageNamed:"minienvelope.tiff"];
	[contentImage getSize:&(theFrame.size)];
	NX_X(&theFrame) = thePoint->x - NX_WIDTH(&theFrame) / 2;
	NX_Y(&theFrame) = thePoint->y - NX_HEIGHT(&theFrame) / 2;
	[self initContent:&theFrame style:NX_PLAINSTYLE
			backing:NX_RETAINED buttonMask:0 defer:NO screen:NULL];
	velocity.x = (random() % HORIZ_JUMPS) - HORIZ_JUMPS / 2;
	velocity.y = (random() % VERT_JUMPS) + MIN_VERT;
	[[self contentView] lockFocus];
	[contentImage composite:NX_COPY toPoint:&zeroPoint];
	[[self contentView] unlockFocus];
	[self orderFront:nil];
	return self;
}

- reInitAt:(NXPoint *)thePoint
{ // re-init the window as above, but for already created window.
	NXSize theSize;
	[contentImage getSize:&theSize];
	[self moveTo:(thePoint->x - theSize.width / 2)
				:(thePoint->y - theSize.height / 2)];
	velocity.x = (random() % HORIZ_JUMPS) - HORIZ_JUMPS / 2;
	velocity.y = (random() % VERT_JUMPS) + MIN_VERT;
	[self orderFront:nil];
	return self;
}

- move
{
	NXRect theFrame;
	[self getFrame:&theFrame];
	[self moveTo:(NX_X(&theFrame) + velocity.x)
				:(NX_Y(&theFrame) + velocity.y)];
	velocity.y -= GRAVITY;
	return self;
}

- (BOOL)onScreen
{
	NXRect theFrame; NXScreen *screen;
	[self getFrame:&theFrame andScreen:&screen];
	// consider us on screen if we're off the top since we'll be
	// coming back down sometime
	if (!screen) { // no screen returned?  Use standard screen size
		if ((NX_MAXX(&theFrame) < 0) || (NX_MAXY(&theFrame) < 0) ||
				(NX_X(&theFrame) > 1120.0)) return NO;
		return YES;
	}
	if ((NX_MAXX(&theFrame) < NX_X(&(screen->screenBounds))) ||
			(NX_X(&theFrame) > NX_MAXX(&(screen->screenBounds))) ||
			(NX_MAXY(&theFrame) < NX_Y(&(screen->screenBounds)))) {
		return NO;
	}
	return YES;
}

@end
