package colro;

import java.awt.image.BufferedImage;

import javax.media.opengl.GL;

import world.GameObject;

public class Map extends GameObject {
	
	private Landscape map;
	
	private double xSize;
	private double ySize;
	private double zSize;
	
	private int xSquares;
	private int zSquares;
	
	public Map(BufferedImage heightMap, double xSize, double ySize, double zSize) {
		
		map = new Landscape(heightMap);
		
		this.xSize = xSize;
		this.ySize = ySize;
		this.zSize = zSize;
		
		xSquares = heightMap.getWidth();
		zSquares = heightMap.getHeight();
	}
	
	public void update() {
		
		map.colorIn(camera, xSize, zSize, xSquares, zSquares);
	}
	
	public void render(GL gl) {
		map.render(gl, xSize, zSize, ySize);
	}
	
	public double getHeightAt(double xPos, double zPos) {
		
		xPos += xSize / 2;
		zPos += zSize / 2;
		
		double squareSizeX = xSize / xSquares;
		double squareSizeZ = zSize / zSquares;
		
		int x = (int) ((double) (xPos) / squareSizeX);
		int z = (int) ((double) (zPos) / squareSizeZ);
		
		double height = ySize / (map.getHighestPoint() - map.getLowestPoint());
		
		double ul = map.getValueAt(x, z) * height;
		double ur = map.getValueAt(x + 1, z) * height;
		double dl = map.getValueAt(x, z + 1) * height;
		double dr = map.getValueAt(x + 1, z + 1) * height;
		
		double xf = (1 / squareSizeX) * (xPos % squareSizeX);
		double zf = (1 / squareSizeZ) * (zPos % squareSizeZ);
		
		ul *= (1 - xf) * (1 - zf);
		ur *= xf * (1 - zf);
		dl *= (1 - xf) * zf;
		dr *= xf * zf;

		return ((ul + ur + dl + dr));
	}
}