# -*- coding: utf-8 -*-

from Components.VariableText import VariableText
from Renderer import Renderer
from time import time, localtime, strftime

from enigma import eLabel

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

		self.enableRemaining = False

	GUI_WIDGET = eLabel

	def applySkin(self, desktop, parent):
		attribs = [ ]
		for (attrib, value) in self.skinAttributes:
			if attrib == "enableRemaining":
				self.enableRemaining = True
			else:
				attribs.append((attrib, value))
		self.skinAttributes = attribs
		return Renderer.applySkin(self, desktop, parent)

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

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

	def eventTimeText(self):
		event = self.source.event
		if event:
			now = int(time())
			begintime = event.getBeginTime()
			start = localtime(begintime)
			duration = event.getDuration()
			endtime = begintime + duration
			end = localtime(endtime)
			if self.enableRemaining and begintime <= now <= endtime:
				return (strftime("%A %%s %B %Y,  %H:%M - ", start) % start[2]) + strftime("%H:%M  ", end) + ("(+%d/%d min)"  % (((endtime - now) / 60), (duration / 60)))
			else:
				return (strftime("%A %%s %B %Y,  %H:%M - ", start) % start[2]) + strftime("%H:%M  ", end) + ("(%d min)"  % (duration / 60))
		return ""

	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 = _("Time information for the selected event not available")
		else:
			self.text = self.eventTimeText()
