#include <GL/glew.h>
#include <iostream>
#include <sstream>
#include "Shader.hpp"

/* Default constructor*/
Shader::Shader() : m_vertex_code("#version 330 core  \n"
                                 "in vec2 in_Vertex; \n"
                                 "in vec3 in_Color;  \n"
                                 "uniform mat4 MVP;  \n"
                                 "out vec3 color;    \n"
                                 "void main(){       \n"
                                 "  gl_Position = MVP * vec4(in_Vertex, 0.0, 1.0); \n"
                                 "  color = in_Color; \n"
                                 "}"),
                   m_fragment_code("#version 330 core \n"" in vec3 color; \n"" out vec4 out_Color; \n"" void main(){ \n"" out_Color = vec4(color, 0.5); \n"" }")
{
}

/*Constructor for shaders using textures. Parameter n is not used, it just allow to create a have another constructor. */
Shader::Shader(int glsl, int n) : m_vertexID(0), m_fragmentID(0), m_programID(0)
{
    std::ostringstream os1, os2;
    os1 << "#version ";
    os1 << glsl;
    os1 << " \n in vec2 in_Vertex; \n in vec2 in_UV; \n out vec2 UV; \n void main(){ \n gl_Position = vec4(in_Vertex, 0.0, 1.0); \n UV = in_UV; \n }";
    os2 << "#version ";
    os2 << glsl;
    os2 << " \n in vec2 UV; \n out vec4 out_Color; \n uniform sampler2D textureSampler; \n void main(){ \n out_Color = texture(textureSampler, UV); \n }";
    m_vertex_code   = os1.str();
    m_fragment_code = os2.str();
    //std::cout << m_vertex_code << std::endl;
    //std::cout << m_fragment_code << std::endl;

    (void)n;
}

/* Construct a Shader reading colors in the VBO. Still used for containers, selection*/
Shader::Shader(int glsl):m_vertexID(0), m_fragmentID(0), m_programID(0){
    std::ostringstream os1, os2;
    os1 << "#version ";
    os1 << glsl;
    os1 << " \n in vec2 in_Vertex; \n in vec3 in_Color; \n uniform mat4 MVP; \n out vec3 color; \n void main(){ \n gl_Position = MVP * vec4(in_Vertex, 0.0, 1.0); \n color = in_Color; \n }";
    os2 << "#version ";
    os2 << glsl;
    os2 << " \n in vec3 color; \n out vec4 out_Color; \n void main(){ \n out_Color = vec4(color, 0.5); \n }";
    m_vertex_code   = os1.str();
    m_fragment_code = os2.str();
    //std::cout << m_vertex_code << std::endl;
    //std::cout << m_fragment_code << std::endl;
}

/* Construct Shaders we use for entities
 param glsl says which version of GL Shading Language we are using
 param rgb define the color
 param shade should be true for states, false either*/
Shader::Shader(int glsl, Element_col r, Element_col g, Element_col b, bool shade):m_vertexID(0), m_fragmentID(0), m_programID(0){
    std::ostringstream os1, os2;
    //std::cout << "rgb" << r << " " << g << " " << b << std::endl;
    os1 << "#version ";
    os1 << glsl;
    os1 << " \n in vec2 in_Vertex; \n ";
    if(shade && glsl<330) //intBits to float is not available, we need a float for shading the state
        os1 << "in float s; \n";
    else if(shade) //intBitsToFloat available -> we can use a char for shade
        os1 << "in int c; \n";
    os1 << "uniform mat4 MVP; \n";
    if(shade)
        os1 << "out float shade; \n";
    os1 << "void main(){ \n gl_Position = MVP * vec4(in_Vertex, 0.0, 1.0); \n";
    if(shade && glsl<330)
        os1 << "shade=s; \n";
    else if(shade)
        os1 << "shade=intBitsToFloat(c); \n";
    os1 << "}";
    os2 << "#version ";
    os2 << glsl;
    os2 << " \n";
    if(shade)
        os2 << "in float shade; \n";
    os2 << "out vec4 outColor; \n void main(){ \n outColor = vec4(";
    if(shade){
        r/=2;
        g/=2;
        b/=2;
    }
    os2 << r;
    if(shade)
        os2 << "*shade";
    os2 << ", ";
    os2 << g;
    if(shade)
        os2 << "*shade";
    os2 << ", ";
    os2 << b;
    if(shade)
        os2 << "*shade";
    os2 << ", 0.5); \n }";
    m_vertex_code   = os1.str();
    m_fragment_code = os2.str();
    //std::cout << "code shaders" << std::endl;
    //std::cout << m_vertex_code << std::endl;
    //std::cout << m_fragment_code << std::endl;

}

/*Desturctor*/
Shader::~Shader()
{
    glDeleteShader(m_vertexID);
    glDeleteShader(m_fragmentID);
    glDeleteProgram(m_programID);
}


Shader& Shader::operator=(Shader const &shaderACopier)
{
    // Copy the code of both vertex and fragment shader

    m_vertex_code = shaderACopier.m_vertex_code;
    m_fragment_code = shaderACopier.m_fragment_code;


    // Load shader

    charger();


    // Return pointer

    return *this;
}

/* Load Shader
 This function should be called before using a shader in paintGL*/
bool Shader::charger()
{

    if(!compilerShader(m_vertexID, GL_VERTEX_SHADER, m_vertex_code))
        return false;
    if(!compilerShader(m_fragmentID, GL_FRAGMENT_SHADER, m_fragment_code))
        return false;


    // Create the program

    m_programID = glCreateProgram();


    // Associate shaders

    glAttachShader(m_programID, m_vertexID);
    glAttachShader(m_programID, m_fragmentID);


    /* Bind input
     in_Vertex = coordinates
     in_Color  = colors
     in_UV     = texture coordinates
     */
    glBindAttribLocation(m_programID, 0, "in_Vertex");
    glBindAttribLocation(m_programID, 1, "in_Color");
    glBindAttribLocation(m_programID, 2, "in_UV");


    // Link program

    glLinkProgram(m_programID);


    // check error

    GLint LinkOK(0);
    glGetProgramiv(m_programID, GL_LINK_STATUS, &LinkOK);


    // if error

    if(LinkOK != GL_TRUE)
    {
        GLint tailleErreur(0);
        glGetProgramiv(m_programID, GL_INFO_LOG_LENGTH, &tailleErreur);
        char *erreur = new char[tailleErreur + 1];
        // Get error
        glGetShaderInfoLog(m_programID, tailleErreur, &tailleErreur, erreur);
        erreur[tailleErreur] = '\0';
        // Affichage de l'erreur
        std::cout << erreur << std::endl;
        delete[] erreur;
        glDeleteProgram(m_programID);

        return false;
    }



    // else no problem

    else{
        m_vertex_code.clear();
        m_fragment_code.clear();
        return true;
    }
}


bool Shader::compilerShader(GLuint &shader, GLenum type, const std::string &code)
{
    // Create shader
    shader = glCreateShader(type);


    // Check error

    if(shader == 0)
    {
        std::cout << "Erreur, le type de shader (" << type << ") n'existe pas" << std::endl;
        return false;
    }


    // Send source code
    const GLchar* chaineCodeSource = code.c_str();
    glShaderSource(shader, 1, &chaineCodeSource, nullptr);
    // Compilation
    glCompileShader(shader);
    // check error

    GLint compilationOK(0);
    glGetShaderiv(shader, GL_COMPILE_STATUS, &compilationOK);


    // If error

    if(compilationOK != GL_TRUE)
    {
        GLint tailleErreur(0);
        glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &tailleErreur);
        char *erreur = new char[tailleErreur + 1];
        // Get the error
        glGetShaderInfoLog(shader, tailleErreur, &tailleErreur, erreur);
        erreur[tailleErreur] = '\0';

        std::cout << erreur << std::endl;

        delete[] erreur;

        glDeleteShader(shader);
        return false;
    }

    // Else we're OK

        else
            return true;
}


// Getter

GLuint Shader::getProgramID() const
{
    return m_programID;
}
