package se.urmo.game.map;

import lombok.Getter;
import lombok.Setter;
import se.urmo.game.graphics.SpriteSheetManager;

import java.awt.image.BufferedImage;

@Getter
@Setter
public class MapTile {
    private final TileType tileType;
    private BufferedImage image;
    private final boolean[][] collisionMask;

    public MapTile(BufferedImage image, TileType type) {
        this.tileType = type;
        this.image = image;
        this.collisionMask = tileType.isSolid() ? createCollisionMask(image) : null;
    }

    public static MapTile byType(TileType type) {
        BufferedImage img = SpriteSheetManager
                .get(type.getSpriteSheet())
                .getSprite(type.getRow(), type.getCol()); // row and col in sprite - not in map!
        return new MapTile(img, type) ;
    }

    private boolean[][] createCollisionMask(BufferedImage img) {
        if(img == null) return null;
        int w = img.getWidth();
        int h = img.getHeight();
        boolean[][] mask = new boolean[h][w];
        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++) {
                int alpha = (img.getRGB(x, y) >> 24) & 0xff;
                mask[y][x] = alpha > 0; // solid if any pixel is visible
            }
        }
        return mask;
    }

    public boolean isSolid() {
        return tileType.isSolid();
    }

    @Override
    public String toString() {
        return "MapTile{" +
                "tileType=" + tileType +
                '}';
    }
}
