from Screens.Screen import Screen
from Components.ActionMap import ActionMap
from Components.EpgList import EPGList, EPG_TYPE_SINGLE, EPG_TYPE_SIMILAR, EPG_TYPE_MULTI
from Components.Label import Label
from Components.Pixmap import Pixmap
from Components.Sources.Event import Event
from Components.Sources.ServiceEvent import ServiceEvent
from Components.Sources.StaticText import StaticText
from RecordTimer import RecordTimerEntry, parseEvent, AFTEREVENT
from enigma import eServiceReference
from ServiceReference import ServiceReference
from time import localtime, time

try:
	from Screens.EpgSelection import EPGSelection, OutdatedEPGSelection
	print "[PowerMetrixFHD] 003 -OK-- EpgSelection"
except:
	print "[PowerMetrixFHD] 003 -NOK- EpgSelection"

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

def EPGSelection__init__(self, session, service, zapFunc=None, eventid=None, bouquetChangeCB=None, serviceChangeCB=None):
	Screen.__init__(self, session)
	self.bouquetChangeCB = bouquetChangeCB
	self.serviceChangeCB = serviceChangeCB
	self.ask_time = -1 #now
	self["key_red"] = StaticText("")
	self.closeRecursive = False
	self.saved_title = None
	self["Service"] = ServiceEvent()
	self["Event"] = Event()
	if isinstance(service, str) and eventid != None:
		self.skinName = "EPGSelectionSimilar"
		self.type = EPG_TYPE_SIMILAR
		self["key_yellow"] = StaticText()
		self["key_blue"] = StaticText()
		self["key_red"] = StaticText()
		self.currentService=service
		self.eventid = eventid
		self.zapFunc = None
	elif isinstance(service, eServiceReference) or isinstance(service, str):
		self.type = EPG_TYPE_SINGLE
		self["key_yellow"] = StaticText()
		self["key_blue"] = StaticText()
		self.currentService=ServiceReference(service)
		self.zapFunc = None
		self.sort_type = 0
		self.setSortDescription()
	else:
		self.skinName = "EPGSelectionMulti"
		self.type = EPG_TYPE_MULTI
		self["key_yellow"] = StaticText(_("Prev"))
		self["key_blue"] = StaticText(_("Next"))
		self["now_button"] = Pixmap()
		self["next_button"] = Pixmap()
		self["more_button"] = Pixmap()
		self["now_button_sel"] = Pixmap()
		self["next_button_sel"] = Pixmap()
		self["more_button_sel"] = Pixmap()
		self["now_text"] = Label()
		self["next_text"] = Label()
		self["more_text"] = Label()
		self["date"] = StaticText()
		self.services = service
		self.zapFunc = zapFunc

	self["key_green"] = StaticText(_("Add timer"))
	self.key_green_choice = self.ADD_TIMER
	self.key_red_choice = self.EMPTY
	self["list"] = EPGList(type = self.type, selChangedCB = self.onSelectionChanged, timer = session.nav.RecordTimer)

	self["actions"] = ActionMap(["EPGSelectActions", "OkCancelActions"],
		{
			"cancel": self.closeScreen,
			"ok": self.eventSelected,
			"timerAdd": self.timerAdd,
			"yellow": self.yellowButtonPressed,
			"blue": self.blueButtonPressed,
			"info": self.infoKeyPressed,
			"red": self.zapTo,
			"input_date_time": self.enterDateTime,
			"nextBouquet": self.nextBouquet, # just used in multi epg yet
			"prevBouquet": self.prevBouquet, # just used in multi epg yet
			"nextService": self.nextService, # just used in single epg yet
			"prevService": self.prevService, # just used in single epg yet
		})
	self["actions"].csel = self
	self.onLayoutFinish.append(self.onCreate)

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

def EPGSelectiononCreate(self):
	l = self["list"]
	l.recalcEntrySize()
	if self.type == EPG_TYPE_MULTI:
		l.fillMultiEPG(self.services, self.ask_time)
		l.moveToService(self.session.nav.getCurrentlyPlayingServiceReference())
	elif self.type == EPG_TYPE_SINGLE:
		service = self.currentService
		self["Service"].newService(service.ref)
		if self.saved_title is None:
			self.saved_title = self.title
		title = self.saved_title + " - " + service.getServiceName()
		self.title = title
		l.fillSingleEPG(service)
	else:
		service = ServiceReference(self.currentService)
		if self.saved_title is None:
			self.saved_title = self.title
		title = self.saved_title + " - " + service.getServiceName()
		self.title = title
		l.fillSimilarList(self.currentService, self.eventid)

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

def EPGSelectionrefillAfterRemoveTimer(self): # AGGIUNTA PER AGGIORNARE DOPO AVER RIMOSSO UN TIMER
	l = self["list"]
	l.recalcEntrySize()
	if self.type == EPG_TYPE_MULTI:
		#l.fillMultiEPG(self.services, self.ask_time)
		l.updateMultiEPG(0)
		#l.moveToService(self.session.nav.getCurrentlyPlayingServiceReference())
	elif self.type == EPG_TYPE_SINGLE:
		service = self.currentService
		event_id = l.getSelectedEventId()
		l.fillSingleEPG(service)
		l.sortSingleEPG(self.sort_type)
		l.moveToEventId(event_id)
	else:
		service = self.currentService
		l.fillSimilarList(service, self.eventid)

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

def EPGSelectionremoveTimer(self, timer):
	timer.afterEvent = AFTEREVENT.NONE
	self.session.nav.RecordTimer.removeEntry(timer)
	self.refillAfterRemoveTimer()
	self["key_green"].setText(_("Add timer"))
	self.key_green_choice = self.ADD_TIMER

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

def EPGSelectiononSelectionChanged(self):
	cur = self["list"].getCurrent()
	if cur is None:
		if self.key_green_choice != self.EMPTY:
			self["key_green"].setText("")
			self.key_green_choice = self.EMPTY
		if self.key_red_choice != self.EMPTY:
			self["key_red"].setText("")
			self.key_red_choice = self.EMPTY
		return
	event = cur[0]
	self["Event"].newEvent(event)
	if self.type == EPG_TYPE_MULTI:
		count = self["list"].getCurrentChangeCount()
		if self.ask_time != -1:
			self.applyButtonState(0)
		elif count > 1:
			self.applyButtonState(3)
		elif count > 0:
			self.applyButtonState(2)
		else:
			self.applyButtonState(1)
		days = [ _("Mon"), _("Tue"), _("Wed"), _("Thu"), _("Fri"), _("Sat"), _("Sun") ]
		datestr = ""
		if event is not None:
			now = time()
			beg = event.getBeginTime()
			nowTime = localtime(now)
			begTime = localtime(beg)
			if nowTime[2] != begTime[2]:
				datestr = '%s %d.%d.'%(days[begTime[6]], begTime[2], begTime[1])
			else:
				datestr = '%s %d.%d.'%(_("Today"), begTime[2], begTime[1])
		self["date"].setText(datestr)
		if cur[1] is None:
			self["Service"].newService(None)
		else:
			self["Service"].newService(cur[1].ref)
	elif self.type == EPG_TYPE_SIMILAR:
		if cur[1] is None:
			self["Service"].newService(None)
		else:
			self["Service"].newService(cur[1].ref)

	if cur[1] is None or cur[1].getServiceName() == "":
		if self.key_green_choice != self.EMPTY:
			self["key_green"].setText("")
			self.key_green_choice = self.EMPTY
		if self.key_red_choice != self.EMPTY:
			self["key_red"].setText("")
			self.key_red_choice = self.EMPTY
		return
	elif self.key_red_choice != self.ZAP and self.type == EPG_TYPE_MULTI:
			self["key_red"].setText("Zap")
			self.key_red_choice = self.ZAP

	if event is None:
		if self.key_green_choice != self.EMPTY:
			self["key_green"].setText("")
			self.key_green_choice = self.EMPTY
		return

	serviceref = cur[1]
	eventid = event.getEventId()
	refstr = serviceref.ref.toString()
	isRecordEvent = False
	for timer in self.session.nav.RecordTimer.timer_list:
		if timer.eit == eventid and timer.service_ref.ref.toString() == refstr:
			isRecordEvent = True
			break

	if isinstance(self, OutdatedEPGSelection):
		return

	if isRecordEvent and self.key_green_choice != self.REMOVE_TIMER:
		self["key_green"].setText(_("Remove timer"))
		self.key_green_choice = self.REMOVE_TIMER
	elif not isRecordEvent and self.key_green_choice != self.ADD_TIMER:
		self["key_green"].setText(_("Add timer"))
		self.key_green_choice = self.ADD_TIMER

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

def OutdatedEPGSelection__init__(self, session, service, zapFunc=None, eventid=None, bouquetChangeCB=None, serviceChangeCB=None):
	Screen.__init__(self, session)
	EPGSelection.__init__(self, session, service, zapFunc, eventid, bouquetChangeCB, serviceChangeCB)
	self.skinName = "OutdatedEPGSelection"

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

def OutdatedEPGSelectiononCreate(self):
	l = self["list"]
	l.recalcEntrySize()
	service = self.currentService
	self["Service"].newService(service.ref)
	if self.saved_title is None:
		self.saved_title = self.title
	title = self.saved_title + " - " + service.getServiceName()
	self.title = title
	l.fillOutdatedSingleEPG(service)

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

def doEpgSelectionChange():
	try:
		EPGSelection.__init__ = EPGSelection__init__
		EPGSelection.onSelectionChanged = EPGSelectiononSelectionChanged
		EPGSelection.onCreate = EPGSelectiononCreate
		EPGSelection.refillAfterRemoveTimer = EPGSelectionrefillAfterRemoveTimer
		EPGSelection.removeTimer = EPGSelectionremoveTimer
		OutdatedEPGSelection.__init__ = OutdatedEPGSelection__init__
		OutdatedEPGSelection.onCreate = OutdatedEPGSelectiononCreate
		print "[PowerMetrixFHD] 003 -OK-- EpgSelection"
	except:
		print "[PowerMetrixFHD] 003 -NOK- EpgSelection"
