#include "Shader.hpp"

#include <iostream>
#include <fstream>
#include <sstream>
#include "../../../../core/utils/logger.hpp"

using namespace pass;

Shader::Shader(GLenum type, const std::string& file_path, const std::vector<std::string>& flags) {
    ShaderID = glCreateShader(type);

    // Load code
    std::string code;
    std::ifstream CodeStream(file_path, std::ios::in);
    CodeStream.exceptions(CodeStream.failbit);

    std::stringstream sstr;
    std::string line;
    std::getline(CodeStream, line);
    sstr << line << std::endl; // version
    // Add flags
    for(auto flag : flags) {
        sstr << "#define " << flag << " 1" << std::endl;
    }
    sstr << CodeStream.rdbuf();
    CodeStream.close();
    code = sstr.str();

    // Compile Shader
    char const *codePtr = code.c_str();
    glShaderSource(ShaderID, 1, &codePtr, NULL);
    glCompileShader(ShaderID);

    // Check Shader
    GLint result = GL_FALSE;
    int infoLogLength;
    glGetShaderiv(ShaderID, GL_COMPILE_STATUS, &result);
    glGetShaderiv(ShaderID, GL_INFO_LOG_LENGTH, &infoLogLength);
    if (infoLogLength > 0) {
        std::string errorMessage(infoLogLength + 1, '\0');
        glGetShaderInfoLog(ShaderID, infoLogLength, NULL, errorMessage.data());
        FATAL("Failed to compile shader " << file_path << ": " << errorMessage);
    }
}
Shader::~Shader() {
    glDeleteShader(ShaderID);
}
