package net.robertboehm.ld22;

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

import org.newdawn.slick.geom.Shape;

public class GameMap implements IEnvironment {

	private final GameMapLayer[] collisionLayers;
	public final GameTileset tileset;
	public final GameMapLayer[] layers;
	public final int width;
	public final int height;
	public final float gravity;
	public final float friction;
	public final String name;
	public final int startX;
	public final int startY;
	
	public GameMap(String name, int startX, int startY, GameMapLayer[] layers, GameTileset tileset, int width, int height, float gravity, float friction) {
		this.name = name;
		this.startX = startX;
		this.startY = startY;
		this.tileset = tileset;
		this.layers = layers;
		this.width = width;
		this.height = height;
		this.gravity = gravity;
		this.friction = friction;
		
		List<GameMapLayer> collisionLayerList = new ArrayList<GameMapLayer>();
		for(GameMapLayer l : layers) {
			if(!l.ignoresCollisions) {
				collisionLayerList.add(l);
			}
		}
		collisionLayers = collisionLayerList.toArray(new GameMapLayer[0]);
	}
	
	@Override
	public boolean intersects(Shape s) {
		int minX = (int)(s.getMinX() / tileset.tileWidth);
		int minY = (int)(s.getMinY() / tileset.tileHeight);
		int maxX = (int)Math.ceil(s.getMaxX() / tileset.tileWidth);
		int maxY = (int)Math.ceil(s.getMaxY() / tileset.tileHeight);
		
		minX = Math.min(this.width - 1, Math.max(0, minX));
		maxX = Math.min(this.width - 1, Math.max(0, maxX));
		minY = Math.min(this.height - 1, Math.max(0, minY));
		maxY = Math.min(this.height - 1, Math.max(0, maxY));
		
		Tile t;
		for(int y = minY; y <= maxY; y++) {
			for(int x = minX; x <= maxX; x++) {
				for(GameMapLayer l : collisionLayers) {
					t = l.getTile(x, y);
					if(t != null && t.intersects(s)) {
						return true;
					}
				}
			}
		}
		return false;
	}

	@Override
	public float getGravity() {
		return gravity;
	}

	@Override
	public float getFriction() {
		return friction;
	}
	
	public int getTileId(int x, int y) {
		return getTileId(x, y, width);
	}
	
	public static int getTileId(int x, int y, int width) {
		return y * width + x;
	}

	public static int getTileY(int id, int width) {
		return id / width;
	}

	public static int getTileX(int id, int y, int width) {
		return id - y * width;
	}
	
}
