textureCache = {}
activeBlendMode = nil


---------------------------
-- Different blending-modes
---------------------------
BlendMode =
{
   NORMAL = 0,
   ADDITIVE = 1,
}


-----------------------
-- Creates a new sprite
-----------------------
function newSprite(imageFile, x, y, w, h)
   local o = {}
   
   
   ----------------------------
   -- Constructor of the sprite
   ----------------------------
   function o:construct(imageFile, x, y, w, h)
      
      if (not textureCache[imageFile]) then
         textureCache[imageFile] = pge.texture.load(imageFile, PGE_RAM)
      end
      
      
      self.image = textureCache[imageFile]
      self.x = x or 0
      self.y = y or 0
      self.w = w or (self.image:width() - self.x)
      self.h = h or (self.image:height() - self.y)
      self.cx = 0
      self.cy = 0
      self.blendMode = BlendMode.NORMAL
      
      return self
   end
   
   
   -------------------------------
   -- Gets the width of the sprite
   -------------------------------
   function o:getWidth()
      return self.w
   end
   
   
   --------------------------------
   -- Gets the height of the sprite
   --------------------------------
   function o:getHeight()
      return self.h
   end
   
   
   --------------------------------------------------------------------------
   -- Sets the center of the sprite
   -- (e.g. (0.5, 0.5) for the center, (0.0, 0.0) for the top-left corner...)
   --------------------------------------------------------------------------
   function o:setCenter(cx, cy)
      self.cx = cx
      self.cy = cy
   end
   
   
   ---------------------------------------
   -- Sets the blending-mode of the sprite
   ---------------------------------------
   function o:setBlendMode(mode)
      self.blendMode = mode
   end
   
   
   -----------------------------------------
   -- Draws the sprite at the given position
   -----------------------------------------
   function o:draw(x, y, angle, sx, sy, alpha)
      angle = angle or 0
      sx = sx or 1
      sy = sy or 1
      alpha = alpha or 255
      
      local w = math.floor(self.w * sx)
      local h = math.floor(self.h * sy)
      
      if (activeResource ~= self.image or activeBlendMode ~= self.blendMode) then
         if (self.blendMode == BlendMode.ADDITIVE) then
            pge.gfx.setblendmode(PGE_BLEND_MODE_TRANSPARENT)
         else
            pge.gfx.setblendmode(PGE_BLEND_MODE_REGULAR)
         end
         activeBlendMode = self.blendMode
      end
      
      if (activeResource ~= self.image) then
         self.image:activate()
         activeResource = self.image
      end
      
      self.image:draw(math.floor(x - self.cx * w), math.floor(y - self.cy * h),
                      w, h, self.x, self.y, self.w, self.h, angle / 57.2958, alpha)
   end
   
   
   return o:construct(imageFile, x, y, w, h)
end
