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

public class Background extends TiledLayer {
	private static final String IMAGE_FILENAME = "/background.png";
	private static final int IMAGE_COLUMNS = 8;
	private static final int IMAGE_ROWS = 2;

	private static final int MAP_COLUMNS = 8;
	private static final int MAP_ROWS = 8;
	private static final int m_map[][] = {
		{  0,  0, -8,  0,  0,  0,  0,  0 },
		{  0,  0, -2,  0,  0,  0,  0,  0 },
		{ -7,  0,-10, -8,  0,  0, -7,  0 },
		{ -3,  0, -1, -4,  0,  0, -4,  0 },
		{-11,  0, -9,-12,  0,  0,-12,  0 },
		{ -1,  0, -4, -3,  0,  0, -2,  0 },
		{ -9,  0,-12,-11,  0,  0,-10,  0 },
		{  5, 15, 14, 13, 16, 15,  6, 16 }
	};
	private static final int m_anims[][] = {
		{ 1,  2,  3,  4},
		{ 2,  3,  4,  1},
		{ 3,  4,  1,  2},
		{ 4,  1,  2,  3},
		{ 5, 13},
		{ 6, 14},
		{ 7,  8},
		{ 8,  7},
		{ 9, 10, 11, 12},
		{10, 11, 12,  9},
		{11, 12,  9, 10},
		{12,  9, 10, 11}
	};
	private static final int ANIM_COUNT = 12;
	private static int m_frameindex[] = new int[ANIM_COUNT];
	private static int m_anim_trigger = 7;
/*
	private static final int m_map[][] = {
		{  0,  0,  8,  0,  0,  0,  0,  0 },
		{  0,  0,  2,  0,  0,  0,  0,  0 },
		{  7,  0, 10,  8,  0,  0,  7,  0 },
		{  3,  0,  1,  4,  0,  0,  4,  0 },
		{ 11,  0,  9, 12,  0,  0, 12,  0 },
		{  1,  0,  4,  3,  0,  0,  2,  0 },
		{  9,  0, 12, 11,  0,  0, 10,  0 },
		{  5, 15, 14, 13, 16, 15,  6, 16 }
	};
*/
	private static Image m_image;
	private static final Image getImage() {
		try {
			m_image = Image.createImage(IMAGE_FILENAME);
		}
		catch (Exception e) {
			System.err.println("Error loading background image");
			return null;
		}
		return m_image;
	}

    public Background() {
		super(MAP_COLUMNS,
			  MAP_ROWS,
			  getImage(),
			  m_image.getWidth() / IMAGE_COLUMNS,
			  m_image.getHeight() / IMAGE_ROWS);

		for (int idx=0; idx<ANIM_COUNT; ++idx) {
			createAnimatedTile(m_anims[idx][0]);
		}
		for (int row=MAP_ROWS-1; row>=0; --row) {
			for (int column=MAP_COLUMNS-1; column>=0; --column) {
				setCell(column, row, m_map[row][column]);
			}
		}
    }

	public void animate() {
		if (--m_anim_trigger == 0) {
			m_anim_trigger = 7;
			for (int idx=ANIM_COUNT-1; idx>=0; --idx) {
				setAnimatedTile(-idx-1, m_anims[idx][m_frameindex[idx]]);
				if (++m_frameindex[idx] >= m_anims[idx].length) {
					m_frameindex[idx] = 0;
				}
			}
		}
	}
}
