#######################################################################
#
#    Next Event Renderer for Dreambox/Enigma-2
#    Coded by Vali (c)2010
#    Support: www.dreambox-tools.info
#
#  This plugin is licensed under the Creative Commons 
#  Attribution-NonCommercial-ShareAlike 3.0 Unported License.
#  To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
#  or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
#
#  Alternatively, this plugin may be distributed and executed on hardware which
#  is licensed by Dream Multimedia GmbH.
#
#  This plugin is NOT free software. It is open source, you are allowed to
#  modify it (if you keep the license), but it may not be commercially 
#  distributed other than under the conditions noted above.
#
#######################################################################

from Components.VariableText import VariableText
from Renderer import Renderer
from enigma import eLabel, eEPGCache, eServiceReference
from time import localtime

class DEMetrixNextEvent(Renderer, VariableText):
	def __init__(self):
		Renderer.__init__(self)
		VariableText.__init__(self)

		self.epgcache = eEPGCache.getInstance()

	GUI_WIDGET = eLabel

	def connect(self, source):
		Renderer.connect(self, source)

	def postWidgetCreate(self, instance):
		VariableText.postWidgetCreate(self, instance)
		instance.setDefaultAnimationEnabled(self.source.isAnimated)

	def nextEvent(self):
		text = "Next event: Not available"
		service = self.source.service
		info = service and self.source.info
		event = self.source.event
		if info and event:
			nextevent = self.epgcache.lookupEventTime(service, event.getBeginTime() + event.getDuration())
			if nextevent:
				begintime = nextevent.getBeginTime()
				duration = nextevent.getDuration()
				endtime = localtime(begintime + duration)
				begintime = localtime(begintime)
				eventname = nextevent.getEventName()
				text = "Next event:  %02d:%02d  %02d:%02d\n" % (begintime[3], begintime[4], endtime[3], endtime[4])
				text += "(%d min) %s" % ((duration / 60), eventname)
		print "[DEMetrixNextEvent] %s" % text
		return text

	def changed(self, what):
		if what[0] == self.CHANGED_ANIMATED and self.instance:
			self.instance.setDefaultAnimationEnabled(self.source.isAnimated)
		elif what[0] == self.CHANGED_CLEAR:
			self.text = ""
		else:
			self.text = self.nextEvent()
