import pygame
import cairo
import cStringIO

class Gfx:
	"""
	The graphics engine. Stores a copy of the display surface and a mini font engine.
	"""
	def __init__(self):
		self.font = {}
		self.SetSize([320, 240])
	
	def SetSize(self, size):
		self.window = pygame.display.set_mode(size)
		self.actualScreen = pygame.display.get_surface()
		self.width = self.actualScreen.get_width()
		self.height = self.actualScreen.get_height()
		# Setup Cairo
		self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.width, self.height)
		self.screen = cairo.Context(self.surface)
	
	def LoadFont(self, fontname, relsize=30, altname=None):
		if not altname:
			altname = fontname
		self.font[altname] = pygame.font.Font("resources/" + fontname + ".ttf", int(self.screen.get_width() * relsize / 1000))
	
	def Caption(self, caption):
		"""
		Set the window caption.
		"""
		pygame.display.set_caption(caption)
	
	def Flip(self):
		"""
		Post rendering stuff such as:
		Flip the pygame display surface.
		"""
		f = cStringIO.StringIO()
		self.surface.write_to_png(f)
		f.seek(0)
		pic = pygame.image.load(f, 'temp.png').convert_alpha()
		self.actualScreen.fill((255, 255, 255))
		self.actualScreen.blit(pic, (0, 0))
		pygame.display.flip()
		self.screen.set_source_rgb(1, 1, 1)
		self.screen.rectangle(0, 0, self.width, self.height)
		self.screen.fill()


# this is a singleton and we always want it instantiated
gfx = Gfx()


