#include <gfx/shader.hpp>
#include <utils/assumptions.hpp>

#include <glad/glad.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

// NOTE: code is largely from https://github.com/JoeyDeVries/LearnOpenGL
// for now I decided not to apply naming_conventions here.

//constructor
Shader::Shader(std::filesystem::path const& vertexPath, std::filesystem::path const& fragmentPath, shader_type _type)
 : type{_type}
{
    ASSUMPTION(std::filesystem::is_regular_file(vertexPath));
    ASSUMPTION(std::filesystem::is_regular_file(fragmentPath));

    // 1. retrieve the vertex/fragment source code from filePath
    std::string vertexCode;
    std::string fragmentCode;
    std::ifstream vShaderFile;
    std::ifstream fShaderFile;
    // ensure ifstream objects can throw exceptions:
    vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
    fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
    try
    {
        // open files
        vShaderFile.open(vertexPath);
        fShaderFile.open(fragmentPath);
        std::stringstream vShaderStream, fShaderStream;
        // read file’s buffer contents into streams
        vShaderStream << vShaderFile.rdbuf();
        fShaderStream << fShaderFile.rdbuf();
        // close file handlers
        vShaderFile.close();
        fShaderFile.close();
        // convert stream into string
        vertexCode = vShaderStream.str();
        fragmentCode = fShaderStream.str();
    }
    catch(std::ifstream::failure e)
    {
        std::cerr << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
    }
    const char* vShaderCode = vertexCode.c_str();
    const char* fShaderCode = fragmentCode.c_str();

    // 2. compile shaders
    unsigned int vertex, fragment;

    // vertex Shader
    vertex = glCreateShader(GL_VERTEX_SHADER);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
    ASSUMPTION(vertex != 0);
    glShaderSource(vertex, 1, &vShaderCode, NULL);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
    glCompileShader(vertex);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
    // print compile errors if any
    checkCompileErrors(vertex, "VERTEX");

    // fragment Shader
    fragment = glCreateShader(GL_FRAGMENT_SHADER);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
    ASSUMPTION(fragment != 0);
    glShaderSource(fragment, 1, &fShaderCode, NULL);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
    glCompileShader(fragment);     
    ASSUMPTION(glGetError() == GL_NO_ERROR);
    checkCompileErrors(fragment, "FRAGMENT");

    // shader Program
    ID = glCreateProgram();
    ASSUMPTION(glGetError() == GL_NO_ERROR);
    ASSUMPTION(ID != 0);
    glAttachShader(ID, vertex);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
    glAttachShader(ID, fragment);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
    // glBindFragDataLocation(ID, 3, "FragColor"); // NOT NECESSARY ? EDIT: DO NOT ENABLE!
    ASSUMPTION(glGetError() == GL_NO_ERROR);
    glLinkProgram(ID);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
    // print linking errors if any
    checkCompileErrors(ID, "PROGRAM");

    // delete shaders; they’re linked into our program and no longer necessary
    glDeleteShader(vertex);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
    glDeleteShader(fragment);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
}

void Shader::use() const
{
    ASSUMPTION(ID != 0);
    glUseProgram(ID);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
}

void Shader::setBool(const GLint location, bool value) const
{
    ASSUMPTION(ID != 0);
    glProgramUniform1i(ID, location, value);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
}
void Shader::setInt(const GLint location, int value) const
{
    ASSUMPTION(ID != 0);
    glProgramUniform1i(ID, location, value);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
}
void Shader::setFloat(const GLint location, float value) const
{
    ASSUMPTION(ID != 0);
    glProgramUniform1f(ID, location, value);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
}
void Shader::setVec3(const GLint location, const glm::vec3 &value) const
{
    ASSUMPTION(ID != 0);
    glProgramUniform3fv(ID, location, 1, glm::value_ptr(value));
    ASSUMPTION(glGetError() == GL_NO_ERROR);
}
void Shader::setVec4(const GLint location, const glm::vec4 &value) const
{
    ASSUMPTION(ID != 0);
    glProgramUniform4fv(ID, location, 1, glm::value_ptr(value));
    ASSUMPTION(glGetError() == GL_NO_ERROR);
}

void Shader::setMat4(const GLint location, const glm::mat4 &value) const
{
    ASSUMPTION(ID != 0);
    glProgramUniformMatrix4fv(ID, location, 1, GL_FALSE, glm::value_ptr(value));
    ASSUMPTION(glGetError() == GL_NO_ERROR);
}

void Shader::setUBO(const GLint binding, GLuint buffer) const
{
    ASSUMPTION(ID != 0);
    // use();
    glBindBufferBase(GL_UNIFORM_BUFFER, binding, buffer);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
}

void Shader::setSSBO(const GLint binding, GLuint buffer) const
{
    ASSUMPTION(ID != 0);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, binding, buffer);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
}

void Shader::setTU(const GLint binding, GLuint texture) const
{
    ASSUMPTION(ID != 0);
    glBindTextureUnit(binding, texture);
    ASSUMPTION(glGetError() == GL_NO_ERROR);
}

Shader::~Shader()
{
    if (ID != 0)
    {
        glDeleteProgram(ID);
        ASSUMPTION(glGetError() == GL_NO_ERROR);
    }
}

// utility function for checking shader compilation/linking errors.
// ------------------------------------------------------------------------
void Shader::checkCompileErrors(unsigned int shader, std::string const& type)
{
    int success;
    char infoLog[1024];
    if (type != "PROGRAM")
    {
        glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
        ASSUMPTION(glGetError() == GL_NO_ERROR);
        if (!success)
        {
            glGetShaderInfoLog(shader, 1024, NULL, infoLog);
            ASSUMPTION(glGetError() == GL_NO_ERROR);
            std::cerr << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
        }
    }
    else
    {
        glGetProgramiv(shader, GL_LINK_STATUS, &success);
        ASSUMPTION(glGetError() == GL_NO_ERROR);
        if (!success)
        {
            glGetProgramInfoLog(shader, 1024, NULL, infoLog);
            ASSUMPTION(glGetError() == GL_NO_ERROR);
            std::cerr << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
        }
    }
}