from PodSix.Concurrent import Concurrent
from PodSix.Rectangle import Rectangle
from PodSix.RDC import RDCEntity

from Collider import Collider
from Platform import Platform

class Character(Concurrent, Collider):
	def __init__(self, rectangle=None):
		Concurrent.__init__(self)
		self.rectangle = Rectangle(rectangle)
		self.hspeed = 0.5
		self.jump = 1.2
		self.level = None
		self.animation = "stand"
		self.velocity = [0, 0]
		self.platform = None
		self.lastplatform = None
	
	def Collide(self, who):
		if isinstance(who, Platform):
			myr = self.rectangle
			thr = who.rectangle
			# figure out which side has penetrated the least
			sides = [
					[thr.Top() - myr.Bottom(), 1, 1],
					[thr.Left() - myr.Right(), 0, 1],
					[myr.Left() - thr.Right(), 0, -1],
					[myr.Top() - thr.Bottom(), 1, -1]
			]
			sides.sort(lambda a, b: cmp(b[0], a[0]))
			d = sides[0]
			
			# if we've hit a platform underneath us
			if (d[1] == 1 and int(d[2]) == 1 and self.platform != who):
				self.platform = who
			
			# move to the outside of the platform on the least penetrated side
			self.rectangle[d[1]] += d[2] * d[0]
			# stop moving if moving toward the platform in the vertical
			if d[1] and d[2] == cmp(self.velocity[d[1]], 0):
				self.velocity[d[1]] = 0
	
	def Update(self):
		self.rectangle.CenterY(self.rectangle.CenterY() + self.velocity[1] * self.Elapsed(0.1))
		self.rectangle.CenterX(self.rectangle.CenterX() + self.velocity[0] * self.Elapsed(0.1))
		Concurrent.Update(self)
		
		if self.velocity[1] > 0:
			self.LeavePlatform()
	
	def SetLevel(self, level):
		self.level = level
	
	def StopRight(self):
		if self.animation == "walk.right":
			self.animation = "stand.right"
		if self.animation.split(".")[1] == "right":
			self.velocity[0] = 0
	
	def StopLeft(self):
		if self.animation == "walk.left":
			self.animation = "stand.left"
		if self.animation.split(".")[1] == "left":
			self.velocity[0] = 0
	
	def WalkRight(self):
		self.animation = self.animation.split(".")[0] + ".right"
		self.velocity[0] = self.hspeed
	
	def WalkLeft(self):
		self.animation = self.animation.split(".")[0] + ".left"
		self.velocity[0] = -self.hspeed
	
	def Jump(self):
		if self.platform:
			self.velocity[1] = -self.jump
			self.Update()
			self.LeavePlatform()
		self.animation = "jump." + self.animation.split(".")[1]
	
	def LeavePlatform(self):
		if self.platform:
			self.lastplatform = self.platform
			self.platform = None
			if self.velocity[0]:
				self.animation = "walk." + self.animation.split(".")[1]
			else:
				self.animation = "stand." + self.animation.split(".")[1]
		else:
			self.animation = "jump." + self.animation.split(".")[1]
		

