from pygame import image
from shortcrust.gl2 import *


class Texture(object):
	def __init__(self, filename, transparency=False, flipped=True):
		texture_img = image.load(filename)
		pixels = image.tostring(texture_img, 'RGBA' if transparency else 'RGB', flipped)
		check_gl_error()
		self.texture_id = glGenTextures(1)
		check_gl_error()
		# print "texture ID: %s" % self.texture_id
		glBindTexture(GL_TEXTURE_2D, self.texture_id)
		check_gl_error()
		glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
		check_gl_error()
		glTexImage2D(
			GL_TEXTURE_2D, 0, GL_RGBA if transparency else GL_RGB, texture_img.get_width(), texture_img.get_height(), 0,
			GL_RGBA if transparency else GL_RGB, GL_UNSIGNED_BYTE, pixels
		)
		check_gl_error()
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
		check_gl_error()
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
		check_gl_error()

	def activate(self, texture_index):
		check_gl_error()
		glActiveTexture(texture_index)
		check_gl_error()
		glBindTexture(GL_TEXTURE_2D, self.texture_id)
		check_gl_error()
