package fun;
import javax.microedition.lcdui.*;
public class T3Board extends Canvas {

	private T3Puzzle puzzle = null;
	private int focusX = 0;
	private int focusY = 0;
	private byte color = RED;

public T3Board(final T3MIDlet midlet, T3Puzzle puzzle){
	setPuzzle(puzzle);
		
	final Command exit = new Command("Exit", Command.EXIT, 0);
	addCommand(exit);

	setCommandListener(new CommandListener(){
		public void commandAction(Command c, Displayable d){
			if(c.equals(exit)){
				midlet.exitPuzzle(getPuzzle());
			}
		}
	});
}


public void paint(Graphics g){
	int x = 0;
	int y = 0;
		
	int width = getWidth();
	int height = getHeight();

	g.setColor(0xFFFFFF);
	g.fillRect(y, x, width, height);

	x = (width - (WIDTH * SIZE)) / 2;
	y = (height - (HEIGHT * SIZE)) / 2;

	for(int row = 0; row < HEIGHT; row++){
		for(int col = 0; col < WIDTH; col++){
			drawCell(g, row, col, x, y);
		}
	}
}

	private void drawCell(Graphics g, int row, int col, int x, int y){
		int index = translate(col, row);

		x += (col * SIZE);
		y += (row * SIZE);

		{
			g.setColor(0x000000);
			if(row < (HEIGHT - 1)){
			g.drawLine(x, y + SIZE, x + SIZE, y + SIZE); // Bottom
			}
			if(col < (WIDTH - 1)){
			g.drawLine(x + SIZE, y, x + SIZE, y + SIZE); // Right
			}
		}

		byte[] board = getPuzzle().getBoard(); 

		if(board[index] != 0){
			g.setColor(board[index] == RED ? 0xFF0000 : 0x0000FF);
			g.fillRect(x + (SIZE - RECT) / 2, y + (SIZE - RECT) / 2, RECT, RECT);
		}
		
		if(this.focusX == col && this.focusY == row){
			g.setColor(0x00FF00);
			g.drawRect(x, y, SIZE, SIZE);
		}
	}

	protected void keyPressed(int key){
		
		switch(getGameAction(key)){
			case LEFT:
				moveFocus(-1, 0);
				break;
			case RIGHT:
				moveFocus(+1, 0);
				break;
			case UP:
				moveFocus(0, -1);
				break;
			case DOWN:
				moveFocus(0, +1);
				break;
			case FIRE:
				fireFocus();
				break;
		}
	}

	private void moveFocus(int dx, int dy){
		this.focusX = Math.max(0, Math.min(WIDTH - 1, this.focusX + dx));
		this.focusY = Math.max(0, Math.min(HEIGHT - 1, this.focusY + dy));

		repaint();
	}

	private void fireFocus(){
		int index = translate(this.focusX, this.focusY);
		byte[] board = getPuzzle().getBoard();
		if(board[index] == 0){
			board[index] = this.color;
			
			switch(this.color){
				case RED:
					this.color = BLUE;
					break;
				case BLUE:
					this.color = RED;
					break;
				default:
					throw new IllegalStateException();
			}
		}
		
		repaint();
	}
	
	private int translate(int x, int y){
		return (y * WIDTH) + x;
	}

	private T3Puzzle getPuzzle(){
		return this.puzzle;
	}
	
	private void setPuzzle(T3Puzzle puzzle){
		this.puzzle = puzzle;
	}

	private static final byte RED = 1;
	private static final byte BLUE = 2;

	private static final int WIDTH = 3;
	private static final int HEIGHT = 3;

	private static final int SIZE = 14;
	private static final int RECT = 10;
}