#include "texture.h"

/* Given an SDL_Surface, creates a GL texture from it. */
/* NOTE: loading only supports RGBA */
void
texture_surface_init(Texture* self, SDL_Surface* surface)
{
	if (!self->isInit)
	{
		glGenTextures(1, &self->handle);
		self->isInit = true;
	}

	self->size[0] = surface->w;
	self->size[1] = surface->h;

	texture_bind(self);

	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_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self->size[0], self->size[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels);

	glGenerateMipmap(GL_TEXTURE_2D);
}

/* Initializes the OpenGL texture, given image data. */
bool
texture_init(Texture* self, const char* path)
{
	SDL_Surface* surface;

	memset(self, '\0', sizeof(Texture));

	surface = IMG_Load(path);

	if (!surface)
	{
		printf(STRING_SDL_IMAGE_ERROR);
		return false;
	}
		
	printf(STRING_SDL_IMAGE_SUCCESS, path);

	texture_surface_init(self, surface);

	SDL_FreeSurface(surface);

	return true;
}

/* Binds a texture. */
void
texture_bind(Texture* self)
{
	glBindTexture(GL_TEXTURE_2D, self->handle);
}

/* Frees texture. */
void
texture_free(Texture* self)
{
	glDeleteTextures(1, &self->handle);
	memset(self, '\0', sizeof(Texture));
}
