package net.robertboehm.ld22;

import java.util.ArrayList;
import java.util.List;

import org.newdawn.slick.Image;
import org.newdawn.slick.Renderable;
import org.newdawn.slick.geom.Line;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.geom.Shape;

public class Tile implements Renderable, ICollidable {
	
	public static final int COLLISION_TOP = 1,
							COLLISION_BOTTOM = 2,
							COLLISION_LEFT = 4,
							COLLISION_RIGHT = 8,
							COLLISION_FILL = 16;
	
	private final Shape[] collisionShapes;
	public final Image tileImage;
	public final int x;
	public final int y;
	
	public Tile(Image tileImage, int collisionMode, int x, int y, GameTileset tileset) {
		this.tileImage = tileImage;
		this.x = x;
		this.y = y;
		List<Shape> collisionShapeList = new ArrayList<Shape>();
		if((collisionMode & COLLISION_FILL) != 0) {
			collisionShapeList.add(new Rectangle(x, y, tileset.tileWidth, tileset.tileHeight));
		} else {
			// COLLISION_FILL overrides everything else!

			if((collisionMode & COLLISION_TOP) != 0)
				collisionShapeList.add(new Line(x, y, x + tileset.tileWidth, y));
			
			if((collisionMode & COLLISION_BOTTOM) != 0)
				collisionShapeList.add(new Line(x, y + tileset.tileHeight, x + tileset.tileWidth, y + tileset.tileHeight));
			
			if((collisionMode & COLLISION_RIGHT) != 0)
				collisionShapeList.add(new Line(x + tileset.tileWidth, y, x + tileset.tileWidth, y + tileset.tileHeight));
			
			if((collisionMode & COLLISION_LEFT) != 0)
				collisionShapeList.add(new Line(x, y, x, y + tileset.tileHeight));
		}
		this.collisionShapes = collisionShapeList.toArray(new Shape[0]);
	}
	
	public boolean intersects(Shape other) {
		for(Shape s : collisionShapes) {
			if(s.intersects(other)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void draw(float x, float y) {
		tileImage.draw(x + this.x, y + this.y);
	}
	
}
