from Components.config import config
from Components.GUIComponent import GUIComponent
from Components.HTMLComponent import HTMLComponent
from Tools.Directories import resolveFilename, SCOPE_CURRENT_SKIN, fileExists
from Tools.LoadPixmap import LoadPixmap
from Tools.PiconResolver import PiconResolver
from enigma import eLabel, eEPGCache, eListbox, eListboxPythonMultiContent, gFont, getDesktop, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_HALIGN_CENTER, RT_VALIGN_CENTER
from ServiceReference import ServiceReference
from skin import TemplatedListFonts, componentSizes
from time import localtime, time

try:
	from Components.EpgList import EPGList, Rect, EPG_TYPE_SINGLE, EPG_TYPE_MULTI, EPG_TYPE_SIMILAR
	print "[PowerMetrixFHD] 000 -OK-- EpgList"
except:
	print "[PowerMetrixFHD] 000 -NOK- EpgList"

SKIN_COMPONENT_KEY = "EPGList"
SKIN_COMPONENT_FONT_SIZE_0 = "fontSize0"
SKIN_COMPONENT_FONT_SIZE_1 = "fontSize1"
SKIN_COMPONENT_ITEM_MARGIN = "itemMargin"
SKIN_COMPONENT_MARGIN = "margin"
SKIN_COMPONENT_ICON_HPOS = "iconHPos"
SKIN_COMPONENT_ICON_HEIGHT = "iconHeight"
SKIN_COMPONENT_ICON_WIDTH = "iconWidth"
SKIN_COMPONENT_SERVICE_MULTI_WIDTH = "serviceMultiWidth"
SKIN_COMPONENT_START_END_MULTI_WIDTH = "startendMultiWidth"
SKIN_COMPONENT_DESC_Y = "descY"
SKIN_COMPONENT_DESC_HEIGHT = "descHeight"
SKIN_COMPONENT_PICON_WIDTH = "piconWidth"

#######################################################################################################################################################

class PiconLoader():
	def __init__(self):
		self.nameCache = { }

	def getPicon(self, sRef):
		pngname = PiconResolver.getPngName(sRef, self.nameCache, self.findPicon)
		if fileExists(pngname):
			print "[PiconLoader] Picon found"
			return LoadPixmap(cached = True, path = pngname)
		else:
			print "[PiconLoader] Picon not found"
			return None

	def findPicon(self, sRef):
		pngname = "%s%s.png" % (config.usage.configselection_piconspath.value, sRef)
		if not fileExists(pngname):
			pngname = ""
		return pngname

#######################################################################################################################################################

def EPGList__init__(self, type=EPG_TYPE_SINGLE, selChangedCB=None, timer=None):
	print "[EPGList__init__] Init EPGList"
	self.days = (_("Mon"), _("Tue"), _("Wed"), _("Thu"), _("Fri"), _("Sat"), _("Sun"))
	self.timer = timer
	self.onSelChanged = []
	if selChangedCB is not None:
		self.onSelChanged.append(selChangedCB)
	GUIComponent.__init__(self)
	self.type = type
	self.l = eListboxPythonMultiContent()

	tlf = TemplatedListFonts()
	sizes = componentSizes[SKIN_COMPONENT_KEY]
	fontSize0 = sizes.get(SKIN_COMPONENT_FONT_SIZE_0, tlf.size(tlf.BIG))
	fontSize1 = sizes.get(SKIN_COMPONENT_FONT_SIZE_1, tlf.size(tlf.SMALL))

	self._font0 = gFont(tlf.face(tlf.BIG), fontSize0)
	self._font1 = gFont(tlf.face(tlf.SMALL), fontSize1)
	self.l.setFont(0, self._font0)
	self.l.setFont(1, self._font1)
	itemHeight = componentSizes.itemHeight(SKIN_COMPONENT_KEY, 30)
	self.l.setItemHeight(itemHeight)

	self._textRenderer = None

	self._itemMargin = sizes.get(SKIN_COMPONENT_ITEM_MARGIN, 10)
	self._margin = sizes.get(SKIN_COMPONENT_MARGIN, 10)
	self._iconWidth = sizes.get(SKIN_COMPONENT_ICON_WIDTH, 21)
	self._iconHeight = sizes.get(SKIN_COMPONENT_ICON_HEIGHT, 21)
	self._iconHPos = sizes.get(SKIN_COMPONENT_ICON_HPOS, 4)
	self._serviceMultiWidth = sizes.get(SKIN_COMPONENT_SERVICE_MULTI_WIDTH, 300)
	self._startendMultiWidth = sizes.get(SKIN_COMPONENT_START_END_MULTI_WIDTH, 150)
	self._descY = sizes.get(SKIN_COMPONENT_DESC_Y, 0)
	self._descHeight = sizes.get(SKIN_COMPONENT_DESC_HEIGHT, itemHeight)
	self._piconWidth = sizes.get(SKIN_COMPONENT_PICON_WIDTH, 50)

	if type in (EPG_TYPE_SINGLE, EPG_TYPE_SIMILAR):
		self.l.setBuildFunc(self.buildSingleEntry)
	else:
		assert(type == EPG_TYPE_MULTI)
		self.l.setBuildFunc(self.buildMultiEntry)
		self.showListPicons = config.usage.configselection_showpicons.value
		self.piconLoader = PiconLoader()

	self.epgcache = eEPGCache.getInstance()
	self.clock_pixmap = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/epgclock.png"))
	self.clock_add_pixmap = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/epgclock_add.png"))
	self.clock_pre_pixmap = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/epgclock_pre.png"))
	self.clock_post_pixmap = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/epgclock_post.png"))
	self.clock_prepost_pixmap = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/epgclock_prepost.png"))

#GUI_WIDGET = eListbox

#######################################################################################################################################################

def EPGListrecalcEntrySizeCLASSIC(self):
	esize = self.l.getItemSize()
	width = esize.width()
	height = esize.height()
	#precalc rect values
	if self.type in (EPG_TYPE_SINGLE, EPG_TYPE_SIMILAR):
		weekday_width = self._calcTextWidth("DDD", font=self._font0, size=esize) + self._itemMargin
		datetime_x = weekday_width
		datetime_width = self._calcTextWidth("00.00, 00:00", font=self._font0, size=esize) + (self._itemMargin * 3)
		desc_x = datetime_x + datetime_width
		desc_width = width - desc_x - self._margin
		self.weekday_rect = Rect(0, 0, weekday_width, height)
		self.datetime_rect = Rect(datetime_x, 0, datetime_width, height)
		self.descr_rect = Rect(desc_x, 0, desc_width, height)
	else: # EPG_TYPE_MULTI
		service_x = self._margin
		service_width = self._serviceMultiWidth
		start_end_x = self._margin + service_width + self._margin
		start_end_width = self._startendMultiWidth
		progress_rect_x = start_end_x
		progress_rect_width = start_end_width
		descr_x = start_end_x + start_end_width + self._margin
		descr_width = width - descr_x - self._margin
		self.service_rect = Rect(service_x, 0, service_width, height)
		self.start_end_rect = Rect(start_end_x, 0, start_end_width, height)
		self.progress_rect = Rect(progress_rect_x, self._itemMargin, progress_rect_width, height - (self._itemMargin * 2))
		self.descr_rect = Rect(descr_x, 0, descr_width, height)

#######################################################################################################################################################

def EPGListrecalcEntrySizeNEW(self):
	esize = self.l.getItemSize()
	width = esize.width()
	height = esize.height()
	#precalc rect values
	if self.type in (EPG_TYPE_SINGLE, EPG_TYPE_SIMILAR):
		weekday_width = self._calcTextWidth("DDD", font=self._font0, size=esize) + self._itemMargin
		datetime_x = weekday_width
		datetime_width = self._calcTextWidth("00.00, 00:00", font=self._font0, size=esize) + (self._itemMargin * 3)
		desc_x = datetime_x + datetime_width
		desc_width = width - desc_x - self._margin
		self.weekday_rect = Rect(0, 0, weekday_width, height)
		self.datetime_rect = Rect(datetime_x, 0, datetime_width, height)
		self.descr_rect = Rect(desc_x, self._descY, desc_width, self._descHeight)
	else: # EPG_TYPE_MULTI
		start_end_x = self._margin
		start_end_width = self._calcTextWidth("00.00 -- 00.00", font=self._font1, size=esize)
		progress_rect_x = start_end_x
		progress_rect_width = start_end_width
		descr_x = start_end_x + start_end_width + self._margin
		descr_width = width - descr_x - self._margin
		self.picon_rect = Rect(0, 0, 0, 0)
		self.start_end_rect = Rect(start_end_x, 0, start_end_width, height)
		self.progress_rect = Rect(progress_rect_x, self._itemMargin, progress_rect_width, height - (self._itemMargin * 2))
		self.descr_rect = Rect(descr_x, self._descY, descr_width, self._descHeight)
		if self.showListPicons:
			offset = self._margin + self._piconWidth
			self.picon_rect = Rect(self._margin, 0, self._piconWidth, height)
			self.start_end_rect = Rect(start_end_x + offset, 0, start_end_width, height)
			self.progress_rect = Rect(progress_rect_x + offset, self._itemMargin, progress_rect_width, height - (self._itemMargin * 2))
			self.descr_rect = Rect(descr_x + offset, self._descY, descr_width - offset, self._descHeight)
	self.esize = esize

#######################################################################################################################################################

def EPGListbuildSingleEntry(self, service, eventId, beginTime, duration, name):
	(clock_pic, rec) = self.getPixmapForEntry(service, eventId, beginTime, duration)
	r1 = self.weekday_rect
	r2 = self.datetime_rect
	r3 = self.descr_rect
	textOffset = r3.left() + self._iconWidth + self._margin
	textWidth = r3.width() - self._iconWidth - self._margin
	t = localtime(beginTime)
	res = [	None, # no private data needed
			(eListboxPythonMultiContent.TYPE_TEXT, r1.left(), r1.top(), r1.width(), r1.height(), 0, RT_HALIGN_RIGHT|RT_VALIGN_CENTER, self.days[t[6]]),
			(eListboxPythonMultiContent.TYPE_TEXT, r2.left(), r2.top(), r2.width(), r1.height(), 0, RT_HALIGN_CENTER|RT_VALIGN_CENTER, "%02d.%02d, %02d:%02d" %(t[2],t[1],t[3],t[4]))
		  ]
	if rec:
		res.extend(((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHABLEND, r3.left(), self._iconHPos, self._iconWidth, self._iconHeight, clock_pic),
					(eListboxPythonMultiContent.TYPE_TEXT, textOffset, r3.top(), textWidth, r3.height(), 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, name, 0xe51400)
				  ))
	else:
		res.append((eListboxPythonMultiContent.TYPE_TEXT, r3.left(), r3.top(), r3.width(), r3.height(), 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, name, 0x70ad11))
	return res

#######################################################################################################################################################

def EPGListbuildMultiEntryCLASSIC(self, changecount, service, eventId, beginTime, duration, EventName, nowTime, service_name):
	(clock_pic, rec) = self.getPixmapForEntry(service, eventId, beginTime, duration)
	r1 = self.service_rect
	r2 = self.progress_rect
	r3 = self.descr_rect
	r4 = self.start_end_rect
	textOffset = r3.left() + self._iconWidth + self._margin
	textWidth = r3.width() - self._iconWidth - self._margin
	res = [ None, # no private data needed
			(eListboxPythonMultiContent.TYPE_TEXT, r1.left(), r1.top(), r1.width(), r1.height(), 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, service_name)
		  ]
	if beginTime is not None:
		if nowTime < beginTime:
			begin = localtime(beginTime)
			end = localtime(beginTime+duration)
			# print "begin", begin
			# print "end", end
			res.append((eListboxPythonMultiContent.TYPE_TEXT, r4.left(), r4.top(), r4.width(), r4.height(), 1,
						RT_HALIGN_CENTER|RT_VALIGN_CENTER, "%02d.%02d - %02d.%02d" %(begin[3], begin[4], end[3], end[4])))
		else:
			percent = (nowTime - beginTime) * 100 / duration
			res.append((eListboxPythonMultiContent.TYPE_PROGRESS, r2.left(), r2.top(), r2.width(), r2.height(), percent))
		if rec:
			res.extend(((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHABLEND, r3.left(), self._iconHPos, self._iconWidth, self._iconHeight, clock_pic),
						(eListboxPythonMultiContent.TYPE_TEXT, textOffset, r3.top(), textWidth, r3.height(), 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, EventName, 0xe51400)
					  ))
		else:
			res.append((eListboxPythonMultiContent.TYPE_TEXT, r3.left(), r3.top(), r3.width(), r3.height(), 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, EventName, 0x70ad11))
	return res

#######################################################################################################################################################

def EPGListbuildMultiEntryNEW(self, changecount, service, eventId, beginTime, duration, EventName, nowTime, service_name):
	(clock_pic, rec) = self.getPixmapForEntry(service, eventId, beginTime, duration)
	print "[EpgList] EPGSelectionMulti service:", service
	picon = None
	r1 = self.picon_rect
	if self.showListPicons:
		picon = self.piconLoader.getPicon(service)
	r2 = self.progress_rect
	r3 = self.descr_rect
	r4 = self.start_end_rect
	eventname = ""
	if EventName:
		eventname = "(%s)" % EventName
	service_width = self._calcTextWidth(service_name, font=self._font0, size=self.esize) + self._itemMargin
	event_x = r3.left() + service_width
	event_width = self.esize.width() - event_x - self._margin
	textOffset = self._iconWidth + self._margin
	res = [ None ] # no private data needed
	res.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHABLEND, r1.left(), r1.top(), r1.width(), r1.height(), picon))
	if beginTime is not None:
		if nowTime < beginTime:
			begin = localtime(beginTime)
			end = localtime(beginTime+duration)
			# print "begin", begin
			# print "end", end
			res.append((eListboxPythonMultiContent.TYPE_TEXT, r4.left(), r4.top(), r4.width(), r4.height(), 1,
						RT_HALIGN_CENTER|RT_VALIGN_CENTER, "%02d.%02d - %02d.%02d" %(begin[3], begin[4], end[3], end[4])))
		else:
			percent = (nowTime - beginTime) * 100 / duration
			res.append((eListboxPythonMultiContent.TYPE_PROGRESS, r2.left(), r2.top(), r2.width(), r2.height(), percent))
	if rec:
		res.extend(((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHABLEND, r3.left(), self._iconHPos, self._iconWidth, self._iconHeight, clock_pic),
					(eListboxPythonMultiContent.TYPE_TEXT, r3.left() + textOffset, r3.top(), service_width, r3.height(), 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, service_name),
					(eListboxPythonMultiContent.TYPE_TEXT, event_x + textOffset, r3.top(), event_width - textOffset, r3.height(), 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, eventname, 0xe51400)
				  ))
	else:
		res.extend(((eListboxPythonMultiContent.TYPE_TEXT, r3.left(), r3.top(), service_width, r3.height(), 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, service_name),
					(eListboxPythonMultiContent.TYPE_TEXT, event_x, r3.top(), event_width, r3.height(), 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, eventname, 0x70ad11)
				  ))
	return res

#######################################################################################################################################################

def doEpgListChange():
	try:
		EPGList.recalcEntrySize = EPGListrecalcEntrySizeNEW
		EPGList.buildSingleEntry = EPGListbuildSingleEntry
		EPGList.buildMultiEntry = EPGListbuildMultiEntryNEW
		EPGList.__init__ = EPGList__init__
		print "[PowerMetrixFHD] 000 -OK-- EpgList"
	except:
		print "[PowerMetrixFHD] 000 -NOK- EpgList"
