
from OpenGL.GL import *
import util, os
from constants import *

class Texture:
    def __init__(self, texname = None, defaultColor = None, colorKey = None, group=0):
        self.defaultColor = defaultColor
        #group = 0    # Turn off texture grouping.
        self.group = group
        if texname:
            filename = os.path.join('data', texname)
            filename += ".png"
            if self.group:
                self.texture = util.loadTextureG(filename, colorKey)
            else:
                self.texture = util.loadTexture(filename, colorKey)
        
        #print "loaded ", filename

    def draw(self, pos=None, color=None, width = TEXSIZE, height = TEXSIZE, rotation=0, offset=None, rotationCenter=None):

        useColor = None
        if color != None:
            util.setColor(color)
            useColor = color
            #print "Color: ", color
        elif self.defaultColor != None:
            useColor = self.defaultColor
            util.setColor(self.defaultColor)
            #print "DefColor: ", self.defaultColor
        else:
            useColor = (1,1,1,1)
            util.setColor((1,1,1,1))
        
        if self.group and rotation == 0:
            if pos == None:
                pos = (0,0)
            #util.queueTex(pos[0], pos[1],self.texture, useColor, width, height) # Comment to disable vertex arrays
            glLoadIdentity()         # Uncomment to disable vertex arrays
            glTranslate(pos[0],pos[1],0)
	    util.drawTileG(width, height, self.texture)

        else:
            #util.drawQueue()  # Comment to disable vertex arrays
        
            if pos != None:
                glLoadIdentity() 
                glTranslate(pos[0], pos[1], 0)
            if rotation != 0:
	        if rotationCenter == None:
		    rotationCenter = (width / 2, height / 2)
		(w,h) = rotationCenter
                glTranslate(w,h,0)
                glRotate(rotation,0,0,1)
                glTranslate(-w,-h,0)
            
            if offset != None:
                glTranslatef(offset[0],offset[1],offset[2])

            if self.group:
                util.drawTileG(width, height, self.texture)
            else:
                util.drawTile(width, height, self.texture)


    def clearGL(self):
        glDeleteTextures(self.texture)
