#import "FishBrain.h"
#import "DuoImage.h"
#import "Thinker.h"
#import <libc.h>
#import <streams/streams.h>

@implementation FishBrain

- changeXDirection
{
	direction = direction ^ 
		(((direction & RIGHT) == RIGHT) ?  RIGHT : LEFT);
	xspeed = (float)(random() % max_X_Speed) / 10.0 + .1;
	
	[body flip:HORIZONTAL];
	return self;
}

- changeYDirection
{
	direction = direction ^ (((direction & UP) == UP) ? UP : DOWN);
 	yspeed = (float)(random() % max_Y_Speed) / 10.0 + .1;
	return self;
}

-init:(NXSize *)drawingSize fishSize:(NXSize *)mysize owner:mybody
{
	const char *ptr;
	int fishSpeed = 10;
	
	ptr = NXGetDefaultValue([NXApp appName], "AquariumFishSpeed");
  	if (ptr)  sscanf (ptr, "%d", &fishSpeed);
	max_X_Speed = fishSpeed * 5;
	max_Y_Speed = fishSpeed * 3;

	body = mybody;

	sizeOfBody = *mysize;
	sizeOfAquar = *drawingSize;
	WIDTH = sizeOfBody.width;
	HEIGHT = sizeOfBody.height;

	srandom(currentTimeInMs());

	xspeed =  (random() % max_X_Speed) / 10.0 + .1;
	yspeed =  (random() % max_Y_Speed) / 10.0 + .1;

	xpos = (random() % 100) * (sizeOfAquar.width - WIDTH) / 100.0;
	ypos = (random() % 100) * (sizeOfAquar.height - HEIGHT) / 100.0;

	direction = direction ^ (random() % 2) ? RIGHT : LEFT;
	direction = direction ^ (random() % 2) ? UP : DOWN;
		
	if ((direction & LEFT) == LEFT) [self changeXDirection];
	
	

	return self;
}

-(float)getXPos 
{
	if ((direction & LEFT) == LEFT) {
		if (xpos < 0.0) {
			xpos = 0.0;
			[self changeXDirection];
			return (xpos += xspeed);
		} else {
			return (xpos -= xspeed);
		}
	} else {
		if (xpos > (sizeOfAquar.width - WIDTH) ) {
			xpos = sizeOfAquar.width - WIDTH;
			[self changeXDirection];
			return (xpos -= xspeed);
		} else {
			return (xpos += xspeed);
		}
	}
	return xpos;
}

-(float)getYPos
{
	if ((direction & DOWN) == DOWN) {
		if (ypos < 0.0) {
			ypos = 0.0;
			[self changeYDirection];
		} else {
			return (ypos -= yspeed);
		}
	} else {
		if (ypos > (sizeOfAquar.height - HEIGHT) ) {
			ypos = sizeOfAquar.height - HEIGHT;
			[self changeYDirection];
		} else {
			return (ypos += yspeed);
		}
	}
	return ypos;
}

-(float)getXSpeed 
{
	return xspeed;
}

-(float)getYSpeed
{
	return yspeed;
}

-(float)getAngle 
{
	return angle;
}

-(int)getDirection 
{
	return direction;
}

-viewDidResize:(NXSize *)newSize
{
	sizeOfAquar = *newSize;
	return self;
}

-(NXPoint)getCurrentPoint 
{
	NXPoint tmp;

	tmp.x = xpos;
	tmp.y = ypos;
	return tmp;
}

@end
