/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "game/renderer/gl/gl_mesh_renderer.hpp"

#include "game/renderer/gl/gl_mesh.hpp"
#include "game/renderer/gl/gl_shader.hpp"
#include "game/renderer/gl/gl_texture.hpp"
#include "game/renderer/camera.hpp"
#include "common/logger.hpp"

using namespace polygun::renderer;

static void legacy_prepare_mesh_array_buffer(GLShader* shader, unsigned buffer, GLenum attrib_type, unsigned attrib_size, const std::string& attrib_name) {
	glBindBuffer(GL_ARRAY_BUFFER, buffer);
	CHECK_GL;
	glVertexAttribPointer(shader->get_attrib_location(attrib_name.c_str()), attrib_size, attrib_type, GL_FALSE, 0, (void*)0);
	CHECK_GL;
	glEnableVertexAttribArray(shader->get_attrib_location(attrib_name.c_str()));
	CHECK_GL;
}

GLMeshRenderer::GLMeshRenderer() :
	m_shader(nullptr),
	m_prev_mesh(nullptr),
	m_prev_texture(nullptr)
{}

void GLMeshRenderer::render(Mesh* mesh, const glm::vec4& color) {
	if(!m_shader) {
		LOG_ERROR("Attempt to render mesh without active shader!");
		return;
	}

	GLMesh* gl_mesh = static_cast<GLMesh*>(mesh);
	if(mesh!=m_prev_mesh) {
		if(m_prev_mesh && !GLEW_ARB_vertex_array_object) {
			glDisableVertexAttribArray(m_shader->get_attrib_location("in_pos"));
			CHECK_GL;
			if(mesh->has_normals()) {
				glDisableVertexAttribArray(m_shader->get_attrib_location("in_normal"));
				CHECK_GL;
			}
			for(size_t i = 0; i<gl_mesh->m_custom_buffers.size(); i++) {
				glDisableVertexAttribArray(m_shader->get_attrib_location(std::string("in_"+std::to_string(i)).c_str()));
				CHECK_GL;
			}
		}

		if(GLEW_ARB_vertex_array_object) {
			glBindVertexArray(gl_mesh->m_vao);
			CHECK_GL;
		}

		if(!GLEW_ARB_vertex_array_object) {
			legacy_prepare_mesh_array_buffer(m_shader, gl_mesh->m_vbo, GL_FLOAT, 3, "in_pos");
			if(mesh->has_normals())
				legacy_prepare_mesh_array_buffer(m_shader, gl_mesh->m_nbo, GL_FLOAT, 3, "in_normal");
			for(size_t i = 0; i<gl_mesh->m_custom_buffers.size(); i++) {
				GLMesh::MeshBuffer& buffer = gl_mesh->m_custom_buffers[i];
				legacy_prepare_mesh_array_buffer(m_shader, buffer.m_id, opengl::var_type_to_glenum(buffer.m_data_type), buffer.m_length, "in_"+std::to_string(i));
			}
		}
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gl_mesh->m_ebo);
		CHECK_GL;

		m_prev_mesh = mesh;
	}

	m_shader->set_uniform("uniform_model", m_transform);
	CHECK_GL;
	m_shader->set_uniform("uniform_view", m_camera->get_view());
	CHECK_GL;
	m_shader->set_uniform("uniform_projection", m_camera->get_projection());
	CHECK_GL;
	m_shader->set_uniform("uniform_color", color);
	CHECK_GL;

	glDrawElements(GL_TRIANGLES, gl_mesh->m_element_count, GL_UNSIGNED_INT, nullptr);
	CHECK_GL;

	m_transform = glm::mat4(1);
}

void GLMeshRenderer::render_textured(Mesh* mesh, Texture* texture) {
	if(!m_shader) {
		LOG_ERROR("Attempt to render mesh without active shader!");
		return;
	}

	GLMesh* gl_mesh = static_cast<GLMesh*>(mesh);
	if(mesh!=m_prev_mesh) {
		if(!mesh->has_texture_uvs()) {
			LOG_ERROR("Attempt to render mesh without texture as textured!");
			return;
		}

		if(m_prev_mesh && !GLEW_ARB_vertex_array_object) {
			glDisableVertexAttribArray(m_shader->get_attrib_location("in_pos"));
			CHECK_GL;
			glDisableVertexAttribArray(m_shader->get_attrib_location("in_uv"));
			CHECK_GL;
			if(mesh->has_normals()) {
				glDisableVertexAttribArray(m_shader->get_attrib_location("in_normal"));
				CHECK_GL;
			}
			for(size_t i = 0; i<gl_mesh->m_custom_buffers.size(); i++) {
				glDisableVertexAttribArray(m_shader->get_attrib_location(std::string("in_"+std::to_string(i)).c_str()));
				CHECK_GL;
			}
		}

		if(GLEW_ARB_vertex_array_object) {
			glBindVertexArray(gl_mesh->m_vao);
			CHECK_GL;
		}

		if(!GLEW_ARB_vertex_array_object) {
			legacy_prepare_mesh_array_buffer(m_shader, gl_mesh->m_vbo, GL_FLOAT, 3, "in_pos");
			legacy_prepare_mesh_array_buffer(m_shader, gl_mesh->m_tbo, GL_FLOAT, 2, "in_uv");
			if(mesh->has_normals())
				legacy_prepare_mesh_array_buffer(m_shader, gl_mesh->m_nbo, GL_FLOAT, 3, "in_normal");
			for(size_t i = 0; i<gl_mesh->m_custom_buffers.size(); i++) {
				GLMesh::MeshBuffer& buffer = gl_mesh->m_custom_buffers[i];
				legacy_prepare_mesh_array_buffer(m_shader, buffer.m_id, opengl::var_type_to_glenum(buffer.m_data_type), buffer.m_length, "in_"+std::to_string(i));
			}
		}
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gl_mesh->m_ebo);
		CHECK_GL;

		m_prev_mesh = mesh;
	}

	if(texture!=m_prev_texture) {
		GLTexture* gl_texture = static_cast<GLTexture*>(texture);
		glActiveTexture(GL_TEXTURE0);
		gl_texture->bind();

		m_shader->set_uniform("uniform_texture_num", 0);
		CHECK_GL;

		m_prev_texture = texture;
	}

	m_shader->set_uniform("uniform_model", m_transform);
	CHECK_GL;

	glDrawElements(GL_TRIANGLES, gl_mesh->m_element_count, GL_UNSIGNED_INT, nullptr);
	CHECK_GL;

	m_transform = glm::mat4(1);
}

void GLMeshRenderer::render_with_multiple_textures(Mesh* mesh, const std::vector<Texture*>& textures) {
	// TODO
}

void GLMeshRenderer::set_shader(Shader* shader) {
	m_shader = static_cast<GLShader*>(shader);
	m_shader->bind();
	CHECK_GL;
}

void GLMeshRenderer::set_camera(Camera* camera) {
	m_camera = camera;
	if(m_shader) {
		m_shader->set_uniform("uniform_view", m_camera->get_view());
		CHECK_GL;
		m_shader->set_uniform("uniform_projection", m_camera->get_projection());
		CHECK_GL;
	}
}

void GLMeshRenderer::set_3d_rendering_mode(bool enable) {
	if(enable)
		glEnable(GL_DEPTH_TEST);
	else
		glDisable(GL_DEPTH_TEST);
	CHECK_GL;
}

void GLMeshRenderer::set_alpha_blending_mode(bool enable) {
	if(enable) {
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}
	else
		glDisable(GL_BLEND);
}
