#include "stdafx.h"
#include "ResourceManagers\Texture.h"
#include "Systems\FileSystem.h"

Texture::Texture(TextureName const name, GLenum const glTextureNum) 
	: _name(name), _glTextureNum(glTextureNum)
{
	// Generate the texture file name
	char filename[_MAX_PATH];
	sprintf_s(filename, _MAX_PATH, "%s%s.png", fileSystem->GetTextureDir() , _name.GetStr());

	// Load the texture file
	int width, height;
	unsigned char *image = SOIL_load_image(filename, &width, &height, 0, SOIL_LOAD_RGBA);
	if(image == NULL)
	{
		throw new std::exception("Unable to load texture.");
	}

	// Store the texture in video memory
	glActiveTexture(GL_TEXTURE0 + _glTextureNum);
	glGenTextures(1, &_glTextureName);
	glBindTexture(GL_TEXTURE_2D, _glTextureName);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);

	// Free the image we loaded
	SOIL_free_image_data(image);

	// Set texture parameters
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	
	_width  = (GLfloat) width;
	_height = (GLfloat) height;
}

Texture::~Texture() 
{ 
	if(_glTextureName > 0) 
	{
		glDeleteTextures(2, &_glTextureName); 
	}
}

TextureName Texture::GetName(void) const
{
	return _name;
}

GLenum Texture::GetGLTextureNum(void) const
{
	return _glTextureNum;
}

GLuint Texture::GetGLTextureName(void) const
{
	return _glTextureName;
}

GLfloat Texture::GetWidth(void) const
{
	return _width;
}

GLfloat Texture::GetHeight(void) const
{
	return _height;
}
