import java.awt.*;

public class SokobanField extends Canvas {
	private Sokoban Sokoban;
	private Image img;
	private Image offscreen;
	private SokobanLevel level;
	private int cellX = 20;
	private int cellY = 20;
	private int borderX = 2;
	private int borderY = 2;

	public SokobanField(Sokoban Sokoban) {
		this.Sokoban = Sokoban;
	}

	public void show(SokobanLevel level) {
		this.level = level;
		setSize(cellX * level.getWidth(), cellY * level.getHeight());
		offscreen =
			Sokoban.createImage(
				cellX * level.getWidth(),
				cellY * level.getHeight());
		level.restart();
		Sokoban.validate();
		repaint();
	}

	public void undo() {
		if (level.undo())
			repaint();
	}

	public void paint(Graphics g) {
		Graphics g2 = offscreen.getGraphics();

		g2.setColor(Sokoban.back);
		g2.fillRect(0, 0, level.getWidth() * cellX, level.getHeight() * cellY);

		for (int x = 0; x < level.getWidth(); x++) {
			for (int y = 0; y < level.getHeight(); y++) {
				int b = level.getCell(x, y);
				if ((b & SokobanLevel.EMPTY) > 0)
					drawEmpty(g2, x, y);
				if ((b & SokobanLevel.TARGET) > 0)
					drawTarget(g2, x, y);
				if ((b & SokobanLevel.BOX) > 0)
					drawBox(g2, x, y);
			}
		}
		drawPlayer(g2, level.getPlayerX(), level.getPlayerY());
		g.drawImage(offscreen, 0, 0, Sokoban);
	}

	public void drawEmpty(Graphics g, int x, int y) {
		g.drawImage(Sokoban.empty, x * cellX, y * cellY, Sokoban);
	}

	public void drawBox(Graphics g, int x, int y) {
		g.drawImage(Sokoban.box, x * cellX, y * cellY, Sokoban);
	}

	public void drawTarget(Graphics g, int x, int y) {
		g.drawImage(Sokoban.target, x * cellX, y * cellY, Sokoban);
	}

	public void drawPlayer(Graphics g, int x, int y) {
		g.drawImage(Sokoban.player, x * cellX, y * cellY, Sokoban);
	}

	public void update(Graphics g) {
		paint(g);
	}

	public void move(int dx, int dy) {
		level.move(dx, dy);
		repaint();
	}

	public SokobanLevel getLevel() {
		return level;
	}
}
