#include "Program.hpp"

#include <algorithm>
#include <stdexcept>
#include "../api/Images.hpp"
#include "core/utils/logger.hpp"

#define CONTENT_DIR "content/"
#define SHADER_DIR CONTENT_DIR "shaders/"
#define TEXTURES_DIR CONTENT_DIR "textures/"

using namespace render::gl::pass;

void Program::load(const std::vector<Shader*>& shaders) {
    ProgramID = glCreateProgram();

    for(auto shader : shaders) {
        glAttachShader(ProgramID, shader->getId());
    }
    glLinkProgram(ProgramID);

    // Check the program
    GLint result = GL_FALSE;
    int infoLogLength;
    glGetProgramiv(ProgramID, GL_LINK_STATUS, &result);
    glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &infoLogLength);
    if (infoLogLength > 0) {
        std::string errorMessage(infoLogLength, '\0');
        glGetProgramInfoLog(ProgramID, infoLogLength, NULL, errorMessage.data());
        FATAL("Failed to link GL program: " << errorMessage);
    }

    for(auto shader : shaders) {
        glDetachShader(ProgramID, shader->getId());
        delete shader;
    }
}
Program::~Program() {
    glDeleteProgram(ProgramID);
}
Shader* Program::loadShader(GLenum type, const std::vector<std::string>& flags) {
    return new Shader(type, SHADER_DIR + getName() + "." + Shader::getExt(type), flags);
}

void Program::useIt() {
    glUseProgram(ProgramID);
}