package uk.ashigaru.game.graphics.renderers;

import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;

import uk.ashigaru.engine.Engine;
import uk.ashigaru.engine.render.Shader;
import uk.ashigaru.engine.render.model.VAO;
import uk.ashigaru.engine.util.Resource;
import uk.ashigaru.game.Game;

public class ScreenRenderer {

	private Shader shader;
	
	private float[] quadVertices;
	private VAO quad;
		
	public ScreenRenderer() {
		Engine.eventDisplayResize.attach((x) -> this.reloadMatrices());
		shader = new Shader(Resource.find("shaders/screen/screen_Vertex.glsl"), Resource.find("shaders/screen/screen_Fragment.glsl"));
		
		this.init();
	}
	
	public void init() {
		this.quadVertices = new float[] {0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f};
		
		this.quad = new VAO();
		this.quad.bind();
		this.quad.buffer(0, 2, quadVertices);
		this.quad.buffer(1, 2, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1);
		this.quad.registerVBOSize("vertices", this.quadVertices.length);
		this.quad.unbind();
		
		reloadMatrices();
	}
	
	public void reloadMatrices() {
		this.shader.bind();
		this.shader.load("projectionMatrix", new Matrix4f().ortho(0, Engine.getWidth(), 0, Engine.getHeight(), 0, 1));
		this.shader.unbind();		
	}
	
	public void render() {
		shader.bind();
		quad.bind();
		GL20.glEnableVertexAttribArray(0);
		GL20.glEnableVertexAttribArray(1);
		
		GL13.glActiveTexture(GL13.GL_TEXTURE0);
		shader.load("colorMap", 0);
		GL11.glBindTexture(GL11.GL_TEXTURE_2D, Game.instance.fbo.colorTextureMap.get(GL30.GL_COLOR_ATTACHMENT0));

		GL13.glActiveTexture(GL13.GL_TEXTURE0 + 1);
		shader.load("normalMap", 1);
		GL11.glBindTexture(GL11.GL_TEXTURE_2D, Game.instance.fbo.colorTextureMap.get(GL30.GL_COLOR_ATTACHMENT1));
		
		GL13.glActiveTexture(GL13.GL_TEXTURE0 + 2);
		shader.load("positionMap", 2);
		GL11.glBindTexture(GL11.GL_TEXTURE_2D, Game.instance.fbo.colorTextureMap.get(GL30.GL_COLOR_ATTACHMENT2));

		GL13.glActiveTexture(GL13.GL_TEXTURE0) ;
		shader.load("lightDir", new Vector3f(0.7f, 1, 0.7f));
		shader.load("transformationMatrix", new Matrix4f().translate(0, 0, 0).scale(Engine.getWidth(), Engine.getHeight(), 1));
		quad.drawArrays(quad.getVBOSize("vertices"));
		GL20.glDisableVertexAttribArray(0);
		GL20.glDisableVertexAttribArray(1);
		quad.unbind();
		shader.unbind();
	}
}
