from tempfile import mkstemp

from pygame.image import load, save, tostring, fromstring
from pygame.draw import lines
from pygame.transform import scale
from pygame import Surface

class Image:
	def __init__(self, file=None, size=None, surface=None, image=None, depth=None):
		if file:
			self.surface = load(file)
		elif size:
			self.surface = Surface(size, depth=depth)
		elif surface:
			self.surface = surface
		elif image:
			self.surface = image.surface.copy()
		else:
			self.surface = None
	
	def ToString(self):
		return tostring(self.surface, "RGBA")
	
	def FromString(self, s, size):
		self.surface = fromstring(s, size, "RGBA", flipped=False)
		return self
	
	def Scale(self, newsize):
		self.surface = scale(self.surface, newsize)
		return self
	
	def Size(self):
		return self.surface.get_size()
	
	def SubImage(self, rectangle):
		return self.__class__(surface=self.surface.subsurface(rectangle))
	
	def Copy(self):
		return self.__class__(surface=self.surface)
	
	def Pixel(self, pos, color=None):
		#print "Pixel", color
		if color:
			self.surface.set_at(pos, color)
			return color
		else:
			return self.surface.get_at(pos)
	
	def TransparentColor(self, color=None):
		if color == -1:
			self.surface.set_colorkey(None)
		elif color != None:
			self.surface.set_colorkey(color)
		return self.surface.get_colorkey()
		
	def Line(self, points, color, closed=False):
		#print "Line", color
		return lines(self.surface, color, closed, points, 1)
	
	def Palette(self, palette=None):
		if palette:
			self.surface.set_palette(palette)
		return self.surface.get_palette()
	
	def Save(self, filename):
		save(self.surface, filename)
	
	def Fill(self, color):
		self.surface.fill(color)
	
	def FloodFill(self, pos, color):
		"""
		Flood fill on a region of non-BORDER_COLOR pixels.
		Adapted from code from here:
		http://markmail.org/message/ktbfpdfkqwo2wpzb#query:python%20fill%20algorithm+page:1+mid:zyarcnkfduhmomjy+state:results
		"""
		#print "FloodFill", color
		x, y = pos
		original = self.surface.get_at(pos)
		if original != color:
			edge = [(x, y)]
			self.Line(((x, y), (x, y)), color)
			#self.surface.set_at((x, y), color)
			while edge:
				newedge = []
				for (x, y) in edge:
					for (s, t) in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
						if s >= 0 and s < self.surface.get_width() and t >= 0 and t < self.surface.get_height() and self.surface.get_at((s, t)) == original:
							self.Line(((s, t), (s, t)), color)
							#self.surface.set_at((s, t), color)
							newedge.append((s, t))
				edge = newedge

