package maze_game.maze;

import static org.lwjgl.opengl.GL11.GL_FLOAT;
import static org.lwjgl.opengl.GL20.glEnableVertexAttribArray;
import static org.lwjgl.opengl.GL20.glVertexAttribPointer;

import org.lwjgl.opengl.GL33;

import maze_game.helpers.MathHelpers;
import maze_game.helpers.vec.Vec2d;
import maze_game.helpers.vec.Vec2i;

public class Maze
{
	public int width;
	public int height;
	public int[] maze;
	public Vec2d player_pos;
	private int vao = -1;
	public int s;
	
	public void bind() {
		
		if(vao == -1) {
			this.init();
		}
		
		GL33.glBindVertexArray(vao);
	}
	
	public void init()
	{
		float[] verticies = MazeDrawer.drawMazeVerticies(maze, width, height);
		
		int vao = GL33.glGenVertexArrays();
		int vbo = GL33.glGenBuffers();
		
		GL33.glBindVertexArray(vao);
		GL33.glBindBuffer(GL33.GL_ARRAY_BUFFER, vbo);
		GL33.glBufferData(GL33.GL_ARRAY_BUFFER, verticies, GL33.GL_STATIC_DRAW);
		
		glVertexAttribPointer(0, 2, GL_FLOAT, false, Float.BYTES * 5, 0);
		glEnableVertexAttribArray(0);
		
		glVertexAttribPointer(1, 3, GL_FLOAT, false, Float.BYTES * 5, 2 * Float.BYTES);
		glEnableVertexAttribArray(1);
		
		this.vao = vao;
		this.s = verticies.length;
	}
	
	public boolean collision(Vec2d pos, int tile) {
		return this.collision(pos.x, pos.y, tile);
	}
	
	public boolean collision(double px, double py, int tile)
	{
		double c = 0.01;
		int x1 = MathHelpers.floor(px + c) + 0;
		int y1 = MathHelpers.floor(py + c) + 0;
		int x2 = MathHelpers.floor(px - c) + 1;
		int y2 = MathHelpers.floor(py - c) + 1;
		
		if(
				x1 < 0 || y1 < 0 || x1 >= width || y1 >= height ||
				x2 < 0 || y2 < 0 || x2 >= width || y2 >= height
		) {
			return false;
		}
		
		if(
				maze[y1 * width + x1] == tile ||
				maze[y2 * width + x1] == tile ||
				maze[y2 * width + x2] == tile ||
				maze[y1 * width + x2] == tile
		) {
			return true;
		}
		
		return false;
	}
}