#include "Shader.h"
#include <fstream>
#include <iostream>

graphics::Shader::Shader() : m_target(0), m_shaderObject(0) {}

graphics::Shader::Shader(const std::string & file, GLenum target) : m_file(file), m_target(target) {
    build();
};

graphics::Shader::~Shader() {
	glDeleteShader(m_shaderObject);
}

void graphics::Shader::build() {
	std::ifstream input(m_file);
	std::string buffer = std::string((std::istreambuf_iterator<char>(input)), (std::istreambuf_iterator<char>())); 
    m_shaderObject = glCreateShader(m_target);
    if (m_shaderObject == 0) {
        std::cout << "UNABLE TO LOAD SHADER " << m_file;
       // exit(1);
    }
    const GLchar * texts[1];
	texts[0] = buffer.c_str();
    GLint lengths[1];
	lengths[0] = buffer.length();
    glShaderSource(m_shaderObject, 1, texts, lengths);
    glCompileShader(m_shaderObject);

    GLint success;
    glGetShaderiv(m_shaderObject, GL_COMPILE_STATUS, &success);

    if (!success) {
        GLchar infoLog[1024];
        glGetShaderInfoLog(m_shaderObject, 1024, NULL, infoLog);
        std::cout << "UNABLE TO LOAD SHADER " << std::endl <<
         infoLog << std::endl << "SOURCE:" << std::endl << buffer.c_str();
        exit(1);
    }
}

void graphics::Shader::bindToProgram(GLuint program) const {
    glAttachShader(program, m_shaderObject);
}
