package mishin870;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.Sprite;

public class UnlimitedTiledLayer{
Image[] t;
int cell;
int widi;
int heii;
public int x=0;
public int y=0;
public boolean visible=true;
int maxIndex;
int ratherX=0;
int ratherY=0;
public int maxW;
public int maxH;

public UnlimitedTiledLayer(Image image,int tileWidth,int tileHeight,int maxW,int maxH){
this.widi = tileWidth;
this.heii = tileHeight;
this.maxW = maxW;
this.maxH = maxH;
cell = 0;
updateImages(image,tileWidth,tileHeight);
}

void updateImages(Image img,int widi,int heii){
int numX = img.getWidth()/widi;
int numY = img.getHeight()/heii;
int numImgs = numX*numY;
maxIndex = numImgs;
t = new Image[numImgs];
for(int ix=0;ix<numX;ix++){
	for(int iy=0;iy<numY;iy++){
		t[ix+iy*numX] = getPartImg(img,ix*widi,iy*heii,widi,heii);
	}
}
}

public void paint(Graphics g){
if(visible){
	int leftX = ratherX%widi;
	int upY = ratherY%heii;
	for(int y=upY-heii;y<maxH;y+=heii){
		for(int x=leftX-widi;x<maxW;x+=widi){
			drawTile(g,x,y);
		}
	}
}
}

void drawTile(Graphics g,int x,int y){
g.drawImage(t[cell],this.x+x,this.y+y,20);
}

static Image getPartImg(Image img,int x, int y, int width, int height)
{
Image ret = Image.createImage(img,x,y,width,height,Sprite.TRANS_NONE);
return ret;
}

public void setPosition(int x,int y){
this.x = x;
this.y = y;
}

public void move(int x,int y){
this.ratherX+=x;
this.ratherY+=y;
if(ratherX>maxW){ratherX=0;}
if(ratherY>maxH){ratherY=0;}
if(ratherX<0){ratherX=maxW-(maxW%widi);}
if(ratherY<0){ratherY=maxH-(maxH%heii);}
}

public void setVisible(boolean visible){
this.visible = visible;
}

public void setCell(int c){
cell = c;
}

}