#include <assert.h>
#include "utils/logger.h"
#include "render/shader.h"
#include "filesystem/filemanager.h"
#include "filesystem/stream.h"

GLuint CreateShader(GLenum shaderType, const char* filename)
{
	StreamBase* stream = g_fileManager->OpenStream( filename, FileAccess::Read );
	if ( !stream )
	{
		Msg( "CreateShader: failed to open file %s", filename );
		assert( 0 );
	}

	stream->seek( SeekDir::End, 0 );
	size_t length = stream->tell();
	stream->seek( SeekDir::Begin, 0 );

	std::string content;
	content.resize( length + 1 );
	stream->readBuffer( (void*)content.data(), length );

	content[length] = '\0';

	const char* contentCStr = content.c_str();

	GLuint shader = glCreateShader(shaderType);
	glShaderSource(shader, 1, &contentCStr, NULL);
	glCompileShader(shader);

	int  success;
	char infoLog[512];
	glGetShaderiv(shader, GL_COMPILE_STATUS, &success);

	if (!success)
	{
		glGetShaderInfoLog(shader, 512, NULL, infoLog);
		Msg("Failed to compile shader %s\n%s", filename, infoLog);
	}

	Msg("created shader from file %s", filename);
	return shader;
}

Shader::Shader() :
	m_name(nullptr),
	m_stride(0),
	m_layout_count(0)
{

}

Shader::~Shader()
{
	if (m_name)
		free( (void*)m_name );

	Destroy();
}

void Shader::Create(const char* name, const char* vsfilepath, const char* psfilepath)
{
	//m_name = strdup( name );

	GLuint vertexShader = CreateShader(GL_VERTEX_SHADER, vsfilepath);
	GLuint fragmentShader = CreateShader(GL_FRAGMENT_SHADER, psfilepath);

	m_program = glCreateProgram();
	glAttachShader(m_program, vertexShader);
	glAttachShader(m_program, fragmentShader);
	AllocateAttributes();
	glLinkProgram(m_program);
	 
	glDeleteShader(vertexShader);
	glDeleteShader(fragmentShader);

	int  success;
	char infoLog[512];
	glGetProgramiv(m_program, GL_LINK_STATUS, &success);

	if (!success)
	{
		glGetProgramInfoLog(m_program, 512, NULL, infoLog);
		Msg("Failed to link program %s", infoLog);
	}
}

void Shader::Destroy()
{
	glDeleteProgram(m_program);
}
