#include "shader.h"

#include <fstream>

Shader::Shader( ShaderType::Enum shaderType ) : m_handle(0), m_type(shaderType)
{
	TRACE();
	m_handle = ::glCreateShader(shaderType);
	ASSERT(m_handle != 0);
}

Shader::~Shader()
{
	if ( m_handle )
	{
		::glDeleteShader(m_handle);
	}

	TRACE();
}

bool Shader::loadFromSource( const char* source )
{
	TRACE();

	// NULL - mówi że source jest zakończone \0
	::glShaderSource(m_handle, 1, &source, NULL);

	// error checking

	return true;
}

bool Shader::loadFromFile( const char* filename )
{
	TRACE();

	bool result = false;
	std::fstream f(filename, std::fstream::in);
	if ( f.is_open() )
	{
		f.seekg(0, std::fstream::end);
		unsigned int len = static_cast<unsigned int>( f.tellg() );
		f.seekg(0, std::fstream::beg);

		char * buffer = new char[len + 1];

		f.read(buffer, len);

		unsigned int readed = static_cast<unsigned int> ( f.gcount() );

		buffer[readed] = '\0';

		if ( this->loadFromSource(buffer) )
		{
			result = true;
		}

		delete [] buffer;
		f.close();
	}

	return result;
}

bool Shader::compile()
{
	TRACE();

	::glCompileShader(m_handle);

	GLint result = 0;
	::glGetShaderiv(m_handle, GL_COMPILE_STATUS, &result);

	return result != GL_FALSE;
}

void Shader::getLog( char* buffer, const unsigned int size )
{
	TRACE();

	::memset(buffer, 0, size);
	::glGetShaderInfoLog(m_handle, size, 0, buffer);
}
