from Converter import Converter
from Poll import Poll
from time import time
from Components.Element import cached, ElementError

class MetrixEventTime(Poll, Converter, object):
	STARTTIME = 0
	ENDTIME = 1
	DURATION = 2
	REMAINING = 3
	PROGRESS = 4
	HAS_TIME = 5
	IS_INPROGRESS = 6

	def __init__(self, type):
		Converter.__init__(self, type)
		Poll.__init__(self)

		self.type = {	"StartTime": 	self.STARTTIME,
						"EndTime":		self.ENDTIME,
						"Duration":		self.DURATION,
						"Remaining":	self.REMAINING,
						"Progress":		self.PROGRESS,
						"HasTime":		self.HAS_TIME,
						"IsInProgress":	self.IS_INPROGRESS,
					}[type] 

		self.poll_interval = 5000
		self.poll_enabled = True

	@cached
	def getTime(self):
		event = self.source.event
		if event is None:
			return None
		if self.type == self.STARTTIME:
			return event.getBeginTime()
		elif self.type == self.ENDTIME:
			return event.getBeginTime() + event.getDuration()
		elif self.type == self.DURATION:
			return event.getDuration()
		elif self.type == self.REMAINING:
			now = int(time())
			start_time = event.getBeginTime()
			duration = event.getDuration()
			end_time = start_time + duration
			if start_time <= now <= end_time:
				return (duration, end_time - now)
			else:
				return (duration, None)
		return None

	time = property(getTime)

	@cached
	def getValue(self):
		event = self.source.event
		if event is None:
			return None
		if self.type == self.PROGRESS:
			now = int(time())
			start_time = event.getBeginTime()
			duration = event.getDuration()
			if start_time <= now <= (start_time + duration) and duration > 0:
				return (now - start_time) * 1000 / duration
			else:
				return None
		return None

	range = 1000
	value = property(getValue)

	@cached
	def getBoolean(self): 
		event = self.source.event
		if self.type == self.HAS_TIME:
			if event is None:
				return False
			else:
				return True
		elif self.type == self.IS_INPROGRESS:
			if event is None:
				return False
			else:
				now = int(time())
				start_time = event.getBeginTime()
				duration = event.getDuration()
				if start_time <= now <= (start_time + duration) and duration > 0:
					return True
				else:
					return False
		return False

	boolean = property(getBoolean) 

	def changed(self, what):
		Converter.changed(self, what)
		if self.type == self.PROGRESS and len(self.downstream_elements):
			if not self.source.event and self.downstream_elements[0].visible:
				self.downstream_elements[0].visible = False
			elif self.source.event and not self.downstream_elements[0].visible:
				self.downstream_elements[0].visible = True