import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;

public class FishSprite extends Sprite {

	public static final int UP = 1;
	public static final int DOWN = 2;
	public static final int LEFT = 3;
	public static final int RIGHT = 4;

	public int m_dx, m_dy;
	public int m_moveX, m_moveY;
	public int m_dxPrevious;

	private int m_minX, m_minY;
	private int m_maxX, m_maxY;

	private static final String IMAGE_FILENAME = "/fishsprite.png";
	private static final int IMAGE_COLUMNS = 5;
	private static final int IMAGE_ROWS = 1;
	private static final int IMAGE_X_MARGIN = 2;
	private static final int IMAGE_Y_MARGIN = 4;

	private static final int ANIM_FACE = 0;
	private static final int ANIM_TAIL = 1;
	private static final int ANIM_RIGHT = 2;
	private static final int ANIM_HIT = 3;
	private static final int m_animations[][] = {
		{0},
		{1},
		{2,2,3,3,3},
		{4}
	};

	private static Image m_fishImage;

	public static final Image getImage() {
		try {
			m_fishImage = Image.createImage(IMAGE_FILENAME);
		}
		catch (Exception e) {
			System.err.println("Error loading fish image");
			return null;
		}
		return m_fishImage;
	}

	public FishSprite(int screenwidth, int screenheight)
	{
		super(getImage(),
			  m_fishImage.getWidth() / IMAGE_COLUMNS,
			  m_fishImage.getHeight() / IMAGE_ROWS);

		int width = getWidth();
		int height = getHeight();

		//set fish movement
		m_moveX = width / 4;
		m_moveY = height / 4;

		//set movement boundaries
		m_minX = -width/2;
		m_minY = 0;
		m_maxX = screenwidth - width/2;
		m_maxY = screenheight - height;

		//center fish on screen center
		setPosition((screenwidth - width)/2,
					(screenheight - height)/2);

		setFrameSequence(m_animations[ANIM_FACE]);
		defineReferencePixel(width/2, 0);
		defineCollisionRectangle(IMAGE_X_MARGIN,
								 IMAGE_Y_MARGIN,
								 width-2*IMAGE_X_MARGIN,
								 height-2*IMAGE_Y_MARGIN);
	}

	public void swim(int direction) {
		switch (direction) {
			case UP:
				m_dy = -m_moveY;
				break;
			case DOWN:
				m_dy = m_moveY;
				break;
			case LEFT:
				m_dx = -m_moveX;
				break;
			case RIGHT:
				m_dx = m_moveX;
				break;
		}
	}
	public void move() {
		int x = getX() + m_dx;
		int y = getY() + m_dy;

		//Check boundaries
		if (x < m_minX) {
			x = m_maxX;
		}
		else if (x > m_maxX) {
			x = m_minX;
		}
		if (y < m_minY) {
			y = m_minY;
		}
		else if (y > m_maxY) {
			y = m_maxY;
		}

		setPosition(x, y);

		//If direction changed, set left/right sequence & transform
		if (m_dxPrevious != m_dx) {
			m_dxPrevious = m_dx;
			if (m_dx < 0) {
				setTransform(TRANS_MIRROR);
				setFrameSequence(m_animations[ANIM_RIGHT]);
			}
			else if (m_dx > 0) {
				setTransform(TRANS_NONE);
				setFrameSequence(m_animations[ANIM_RIGHT]);
			}
		}
		else {
			nextFrame();
		}

		m_dx = 0;
		m_dy = 0;
	}
}
