#include "GL/gl3w.h"
#include "GL/gl.h"
#include "ShaderPart.hpp"

#include "Debug.hpp"
#include <fstream>
#include "PathHelper.hpp"

void TSE::OpenGL::ShaderPart::Init(const string &str, int shaderType)
{
    shaderPartID = glCreateShader(shaderType);
    const char * cstr = str.c_str();
    int length = str.length();
    glShaderSource(shaderPartID, 1, &cstr, &length);
    glCompileShader(shaderPartID);

    int success;
    glGetShaderiv(shaderPartID, GL_COMPILE_STATUS, &success);

    if(success == GL_FALSE)
    {
        int errorLength = 255;
        char* log = new char[errorLength];
        glGetShaderInfoLog(shaderPartID, errorLength, &errorLength, log);

        TSE_ERROR(log);
    }
}

TSE::OpenGL::ShaderPart::~ShaderPart()
{
    glDeleteShader(shaderPartID);
}

std::unique_ptr<TSE::OpenGL::ShaderPart> TSE::OpenGL::ShaderPart::LoadFromString(const std::string &str, int shaderType)
{
    if (str.length() == 0) throw;
    std::unique_ptr<ShaderPart> shader = std::make_unique<ShaderPart>();
    shader->Init(str, shaderType);
    return shader;
}

std::unique_ptr<TSE::OpenGL::ShaderPart> TSE::OpenGL::ShaderPart::LoadFromPath(const std::string &path, int shaderType)
{
    std::ifstream stream;
    OpenFileReading(stream, path);
    std::string filecontent((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());
    return LoadFromString(filecontent, shaderType);
}
