from entities.Human import Human
from entities.UfoBaddy import UfoBaddy
from entities.MountainRange import MountainRange
from entities.Circle import Circle
from random import randint
import weakref

class Level:
	"""
	A level full of background objects an people to pick up.
	"""
	def __init__(self, world, levelsize=10, difficulty=0):
		# holds a list of all the entities in this world
		self.entities = []
		# things that don't move or update
		self.static = []
		self.levelsize = levelsize
		self.world = world
		
		self.player = world.player
		# whether this level is complete or not
		self.complete = False
		# bounding box of the screen
		self.worldBB = world.worldBB
		
		# weakly referenced dictionary of all of the humans
		self.humans = weakref.WeakKeyDictionary()
		self.ufos = weakref.WeakKeyDictionary()
		
		for i in range(randint(difficulty, difficulty + 3)):
			ufo = UfoBaddy(world, levelsize=levelsize, difficulty=difficulty)
			self.entities.append(ufo)
			self.ufos[ufo] = True
		
		# make some people on the ground
		human = Human(world)
		self.entities.append(human)
		self.humans[human] = True
		
		for i in range(randint(difficulty + 3, difficulty + 6)):
			human = Human(world, levelsize=levelsize)
			self.entities.append(human)
			self.humans[human] = True
		
		# make some static mountains
		for i in range(3):
			self.static.append(MountainRange(world, levelsize))
		# self.static.sort(lambda x, y: cmp(x.height * x.scale, y.height * y.scale))
		self.static.append(Circle())
	
	def Update(self):
		# update what the player is doing
		self.player.Update()
		# update all entities that need it
		[e.Update() for e in self.entities]
		# test for collisions with the player
		self.player.TestCollisions([e for e in self.entities if e.GetBoundingBox().colliderect(self.worldBB)])
		# tell all AIs what is near them
		[u.NearEnemy(self.player) or u.NearHumans(self.humans) or u.TestCollisions(self.humans) for u in self.ufos]
		self.complete = (len([h for h in self.humans if h.alive]) == 0)
	
	def Draw(self):
		"""
		Draw the foreground elements of this level (infront of the player).
		"""
		[s.Draw() for s in self.static]
		self.player.Draw()
		[e.Draw() for e in self.entities if e.GetBoundingBox().colliderect(self.worldBB)]
	
	def RemoveEntity(self, which):
		self.entities.remove(which)
	

