/*
PolyGun

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

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_shader.hpp"

#include <fstream>
#include <sstream>

#include "common/logger.hpp"

using namespace polygun::renderer;

GLShader::GLShader() :
	m_program(glCreateProgram()),
	m_uniform_locations(),
	m_attrib_locations()
{}

GLShader::~GLShader() {
	glDeleteProgram(m_program);
}

void GLShader::bind() {
	glUseProgram(m_program);
}

void GLShader::set_uniform(const GLchar* u_name, unsigned int value) {
	glUniform1i(get_uniform_location(u_name), value);
}

void GLShader::set_uniform(const GLchar* u_name, int value) {
	glUniform1i(get_uniform_location(u_name), value);
}

void GLShader::set_uniform(const GLchar* u_name, GLfloat value) {
	glUniform1i(get_uniform_location(u_name), value);
}

void GLShader::set_uniform(const GLchar* u_name, GLfloat x, GLfloat y) {
	glUniform2f(get_uniform_location(u_name), x, y);
}

void GLShader::set_uniform(const GLchar* u_name, GLfloat x, GLfloat y, GLfloat z) {
	glUniform3f(get_uniform_location(u_name), x, y, z);
}

void GLShader::set_uniform(const GLchar* u_name, const glm::vec3& vector) {
	glUniform3f(get_uniform_location(u_name), vector.x, vector.y, vector.z);
}

void GLShader::set_uniform(const GLchar* u_name, GLfloat x, GLfloat y, GLfloat z, GLfloat w) {
	glUniform4f(get_uniform_location(u_name), x, y, z, w);
}

void GLShader::set_uniform(const GLchar* name, const glm::mat4 &mat) {
	glUniformMatrix4fv(get_uniform_location(name), 1, GL_FALSE, &mat[0][0]);
}

void GLShader::set_uniform(const GLchar* u_name, const glm::vec2& vector) {
	glUniform2f(get_uniform_location(u_name), vector.x, vector.y);
}

void GLShader::set_uniform(const GLchar* u_name, const glm::vec4& vector){
	glUniform4f(get_uniform_location(u_name), vector.x, vector.y, vector.z, vector.w);
}

void GLShader::set_uniform(const GLchar* u_name, GLuint tex2d, GLint unit){ // sample 2d
	glActiveTexture(GL_TEXTURE0 + unit);
	glBindTexture(GL_TEXTURE_2D, tex2d);
	glUniform1i(get_uniform_location(u_name), unit);
}

GLuint GLShader::get_attrib_location(const GLchar* a_name) {
	if(GLEW_ARB_vertex_array_object)
		LOG_WARNING("get_attrib_location used even if VAO is available");
	std::string name(a_name);
	if(m_attrib_locations.count(name))
		return m_attrib_locations[name];
	return (m_attrib_locations[name] = glGetAttribLocation(m_program, a_name));
}

bool GLShader::load_from_file(const std::string& name) {
	std::string base_shader_path;
	// if VAO is available use shaders which use it
	if(GLEW_ARB_vertex_array_object)
		base_shader_path = "shaders/gl/";
	else
		base_shader_path = "shaders/gl2/";
	std::string vertex_code;
	std::string fragment_code;
	std::ifstream v_shader_file;
	std::ifstream f_shader_file;
	v_shader_file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
	f_shader_file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
	try {
		v_shader_file.open(base_shader_path+name+"_vertex.glsl");
		f_shader_file.open(base_shader_path+name+"_fragment.glsl");
		std::stringstream v_shader_stream, f_shader_stream;
		v_shader_stream << v_shader_file.rdbuf();
		f_shader_stream << f_shader_file.rdbuf();
		v_shader_file.close();
		f_shader_file.close();
		vertex_code = v_shader_stream.str();
		fragment_code = f_shader_stream.str();
	}
	catch (std::ifstream::failure& e) {
		LOG_ERROR("Shader file wasn't successfuly read: %s", e.what());
		return false;
	}
	const char* v_shader_code = vertex_code.c_str();
	const char * f_shader_code = fragment_code.c_str();
	unsigned int vertex, fragment;
	vertex = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertex, 1, &v_shader_code, NULL);
	glCompileShader(vertex);
	if(!check_compile_errors(vertex, "VERTEX"))
		return false;
	fragment = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragment, 1, &f_shader_code, NULL);
	glCompileShader(fragment);
	if(!check_compile_errors(fragment, "FRAGMENT"))
		return false;
	glAttachShader(m_program, vertex);
	glAttachShader(m_program, fragment);
	glLinkProgram(m_program);
	if(!check_compile_errors(m_program, "PROGRAM"))
		return false;
	glDeleteShader(vertex);
	glDeleteShader(fragment);
	return true;
}

GLint GLShader::get_uniform_location(const GLchar* u_name) {
	std::string name(u_name);
	if(m_uniform_locations.count(name))
		return m_uniform_locations[name];
	return (m_uniform_locations[name] = glGetUniformLocation(m_program, u_name));
}

bool GLShader::check_compile_errors(GLuint shader, const std::string& type) {
	GLint success;
	GLchar info_log[1024];
	if(type != "PROGRAM") {
		glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
		if(!success) {
			glGetShaderInfoLog(shader, 1024, NULL, info_log);
			LOG_ERROR("%s shader compilation error:\n%s", type.c_str(), info_log);
			return false;
		}
	}
	else {
		glGetProgramiv(shader, GL_LINK_STATUS, &success);
		if(!success) {
			glGetProgramInfoLog(shader, 1024, NULL, info_log);
			LOG_ERROR("%s compilation error:\n%s", type.c_str(), info_log);
			return false;
		}
	}
	return true;
}
