#include "texturelayer.h"
#include "texture.h"
#include "engineinterface.h"
#include "m3derror.h"
#include "openglstate.h"

namespace M3D
{

TextureLayer::TextureLayer()
		: MaterialLayer(),
		_texture_path_( "" ),
		_texture_( 0 ),
		_tex_id_( 0, 0 )
{}


TextureLayer::~TextureLayer()
{}
void TextureLayer::set_layer(OpenGLState *state)
{
	glActiveTexture(_texture_unit_);
	_texture_->bind();
	int programID = state->get_current_program();
	GLint location = glGetUniformLocation ( programID, (_layer_name_ + "Texture").c_str() );
	if(location==-1)/*THROW("Unable to find " + (_layer_name_ + "Texture") + " in shader program")*/;
	else glUniform1i ( location, _texture_unit_ - GL_TEXTURE0 );
}

void TextureLayer::load( const std::string &base_dir, M3DML_BLOCK_TYPE block_type, const M3DML_Layer *layer, EngineInterface *engine )
{
	_layer_type_ = block_type;
	_texture_path_ = layer->texture_path;
	_tex_id_ = engine->create_texture();
	_texture_ = engine->_get_texture( _tex_id_ );
	_texture_->load( base_dir + _texture_path_ );
	set_layer_type();
	switch (_layer_type_)
	{
		case M3DML_DIFFUSE: _texture_unit_ = GL_TEXTURE0; break;
		case M3DML_AMBIENT: _texture_unit_ = GL_TEXTURE1; break;
		case M3DML_SHININESS: _texture_unit_ = GL_TEXTURE2; break;
		case M3DML_SPECULAR: _texture_unit_ = GL_TEXTURE3; break;
		case M3DML_EMISSION: _texture_unit_ = GL_TEXTURE4; break;
		case M3DML_NORMAL_MAP: _texture_unit_ = GL_TEXTURE5; break;
		case M3DML_BUMP_MAP: _texture_unit_ = GL_TEXTURE6; break;
		case M3DML_ROUGHNESS: _texture_unit_ = GL_TEXTURE7; break;
		default: THROW("Invalid layer type");
	}

}

}
