import csv

from item import Item

class ItemManager:
	def __init__(self, application):
		self.application = application

		self.items = []

		self.gen_stream_ids1 = []
		self.gen_stream_ids2 = []
	# __init__

	def add(self, item):
		self.items.append(item)
	# add

	def update(self):
		self.application.teste_id1 = None
		self.application.teste_id2 = None

		for item in self.active_items:
			item.update()
		# for

		for item in self.active_items:
			if item.mouse_over(): continue
		# for
	# update

	def draw(self, surface, real_surface):
		self.application.to_blit_surface = None
		self.application.to_blit_pos = None

		for item in self.active_items:
			item.draw(surface, real_surface)
		# for
	# draw

	def load(self, csv_file_path):
		with open(csv_file_path, 'rb') as csv_file:
			csv_file.readline()
			reader = csv.reader(csv_file, delimiter=',')

			for row in reader:
				item = Item(self.application, int(row[0]), int(row[1]), float(row[2]), float(row[3]), float(row[4]))

				self.add(item)
			# for
		# with

		self.application.slider.build_times(map(lambda item: item.begin_time_point, self.items)+map(lambda item: item.end_time_point, self.items))
		self.load_active_items()

		self.gen_stream_ids1 = list(set(map(lambda item: item.stream_id1, self.items)))
		self.gen_stream_ids2 = list(set(map(lambda item: item.stream_id2, self.items)))
	# load

	def load_active_items(self):
		self.active_items = [item for item in self.items if item.in_time()]
	# load_active_items

	def stream_ids1(self):
		# ids = list(set(map(lambda item: item.stream_id1, self.active_items)))
		# ids.sort()

		# return ids
		return self.gen_stream_ids1
	# stream_ids1

	def stream_ids2(self):
		# ids = list(set(map(lambda item: item.stream_id2, self.active_items)))
		# ids.sort()

		# return ids
		return self.gen_stream_ids2
	# stream_ids2

	def get_pos_x(self, stream_id2):
		ids = self.stream_ids2()

		max_stream_id2 = max(ids)
		min_stream_id2 = min(ids)

		try:
			return (stream_id2-min_stream_id2)*((self.application.grid.rect.width-Item.radius*2)/float(max_stream_id2-min_stream_id2))
		except ZeroDivisionError:
			return 0
		# try
	# get_pos_x

	def get_pos_y(self, stream_id1):
		ids = self.stream_ids1()
		max_stream_id1 = max(ids)
		min_stream_id1 = min(ids)

		try:
			return (stream_id1-min_stream_id1)*((self.application.grid.rect.height-Item.radius*2)/float(max_stream_id1-min_stream_id1))
		except ZeroDivisionError:
			return 0
		# try
	# get_pos_y

	def get_pos(self, item):
		if item.__class__.__name__ == 'Item':
			streams = [item.stream_id1, item.stream_id2]
		else:
			streams = item
		# if

		return self.get_pos_x(streams[1])+Item.radius, self.application.grid.rect.height-self.get_pos_y(streams[0])-Item.radius
	# get_pos
# ItemManager