package game;

import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.LayerManager;
import javax.microedition.lcdui.game.TiledLayer;

/**
 *
 * @author user
 */

public class TL implements L {
    
    private int wSize, hSize, mWidth, mHeight, lX, lY, lpX, lpY, lPartW, lPartH, lPartTiledW, lPartTiledH, lPartsW, lPartsH;
    private TiledLayer[][] tl;
    
    public TL(int col, int row, Image tile, int tWidth, int tHeight, int[][] tiles, int sWidth, int sHeight) {
        wSize = col;
        hSize = row;
        mWidth = wSize*tWidth;
        mHeight = hSize*tHeight;
        lPartW = sWidth/tWidth;
        lPartH = sHeight/tHeight;
        if(lPartW*tWidth < sWidth) lPartW++;
        if(lPartH*tHeight < sHeight) lPartH++;
        lPartTiledW = lPartW*tWidth;
        lPartTiledH = lPartH*tHeight;
        lPartsW = col/lPartW;
        lPartsH = row/lPartH;
        if(lPartsW*lPartW < col) lPartsW++;
        if(lPartsH*lPartH < row) lPartsH++;
        tl = new TiledLayer[lPartsW][lPartsH];
        for(int i=0; i<lPartsW; i++) {
            for(int j=0; j<lPartsH; j++) {
                tl[i][j] = new TiledLayer(lPartW, lPartH, tile, tWidth, tHeight);
            }
        }
        for(int i=0; i<row; i++) {
            for(int j=0; j<col; j++) {
                tl[j/lPartW][i/lPartH].setCell(j-j/lPartW*lPartW, i-i/lPartH*lPartH, tiles[i][j]);
            }
        }
    }
    
    public void appendTo(LayerManager lm, int x, int y) {
        lX = x;
        lY = y;
        for(int i=0; i<lPartsW; i++) {
            for(int j=0; j<lPartsH; j++) {
                tl[i][j].setPosition(x+i*lPartTiledW, y+j*lPartTiledH);
                lm.append(tl[i][j]);
            }
        }
    }
    
    public int getWidth() {
        return mWidth;
    }
    
    public int getHeight() {
        return mHeight;
    }
    
    public int getColumns() {
        return wSize;
    }
    
    public int getRows() {
        return hSize;
    }
    
    public int getCell(int col, int row) {
        return tl[col/lPartW][row/lPartH].getCell(col-col/lPartW*lPartW, row-row/lPartH*lPartH);
    }
    
    public void setCell(int col, int row, int tile) {
        tl[col/lPartW][row/lPartH].setCell(col-col/lPartW*lPartW, row-row/lPartH*lPartH, tile);
    }
    
    public void check(int x, int y, int sWidth, int sHeight) {
        for(int i=0; i<lPartsW; i++) {
            for(int j=0; j<lPartsH; j++) {
                lpX = lX+i*lPartTiledW;
                lpY = lY+j*lPartTiledH;
                if(lpX+lPartTiledW > x-sWidth && lpX < x+sWidth && lpY+lPartTiledH > y-sHeight && lpY < y+sHeight) {
                    if(!tl[i][j].isVisible()) tl[i][j].setVisible(true);
                } else {
                    if(tl[i][j].isVisible()) tl[i][j].setVisible(false);
                }
            }
        }
    }
    
}
