# -*- coding: utf-8 -*-
from gLocale import _
from gTools import cleanexit, dayStrSmall, gLoadPixmap, getEntryString, ctoolsclass
from plugin import cgevent

from enigma import eEPGCache, eServiceReference

from WidgetVariableList import WidgetVariableList
from WidgetConfig import gConfigWindow, gConfigSelection, CONFIGSEPERATOR
from Components.config import config, NoSave, getConfigListEntry, ConfigText

from Screens.MessageBox import MessageBox
from Screens.EventView import EventViewSimple
from ServiceReference import ServiceReference

from time import localtime

class EPGSearch(gConfigWindow):
	def __init__(self, session):
		gConfigWindow.__init__ (self, session, _("EPG Search"), greenbutton=_("Start"), icon="icon_epgsearch.png")
		self.selected=0
		config.bp.sin = NoSave(gConfigSelection(default=cgevent.getConfig("EPGsearch_in", 0), choices=[(0, _("for exact Title")),(1, _("in Title")),(2, _("in Description")),(3, _("in Title or in Description"))]))
		config.bp.sstr= NoSave(ConfigText(default=cgevent.getConfig("EPGsearch_string",_("what")), fixed_size=False))
		self.onLayoutFinish.append(self.__fillListe)
		
	def KeyExit(self):
		self.close()
		cleanexit(__name__)

	def __fillListe(self):
		list = []
		list.append(getConfigListEntry(_("search in") + ":", config.bp.sin))
		list.append(getConfigListEntry(_("Text") + ":", config.bp.sstr))
		self.SetConfList(list)
		self.SetIndex(1)
		
	def SelectionChangedNow(self):
		gConfigWindow.SelectionChangedNow(self)
		sel = self.getCurrendValue()
		if sel and sel == config.bp.sstr:
			self.setRB(_("current"))
			self.selected=1
		else:
			self.setRB()
			self.selected=0
			
	def KeyRed(self):
		if self.selected==1:
			service = self.session.nav.getCurrentService()
			if service:
				info = service.info()
				if info:
					event = info.getEvent(0)
					if event:
						config.bp.sstr.value = event.getEventName()
			self.__fillListe()
		
	def KeyGreen(self):
		list = None
		sstr=config.bp.sstr.value
		cgevent.setConfig("EPGsearch_string", sstr)
		cgevent.setConfig("EPGsearch_in", config.bp.sin.value)
		
		try:
			epg_cache = eEPGCache.getInstance()
			if config.bp.sin.value == 0:
				list = epg_cache.search(('RIBNDT', 100, eEPGCache.EXAKT_TITLE_SEARCH, sstr, eEPGCache.NO_CASE_CHECK)) or []
			elif config.bp.sin.value == 1:
				list = epg_cache.search(('RIBNDT', 100, eEPGCache.PARTIAL_TITLE_SEARCH, sstr, eEPGCache.NO_CASE_CHECK)) or []
			elif config.bp.sin.value == 2:
				list = epg_cache.search(('RIBNDT', 100, eEPGCache.PARTIAL_DESCRIPTION_SEARCH, sstr, eEPGCache.NO_CASE_CHECK)) or []
			else:
				list = epg_cache.search(('RIBNDT', 100, eEPGCache.PARTIAL_DESCRIPTION_SEARCH, sstr, eEPGCache.NO_CASE_CHECK)) or []
				list_title = epg_cache.search(('RIBNDT', 100, eEPGCache.PARTIAL_TITLE_SEARCH, sstr, eEPGCache.NO_CASE_CHECK)) or []
				[ list.append(x) for x in list_title if x not in list ]
			
		except:
			pass

		if list and len(list):
			list.sort(key=lambda x: x[2])
			self.SetIndex(0)#wegen VirtualKeyboard
			self.session.open(EPGSearchView,list,sstr)
		else:
			self.session.open(MessageBox, (_("'%s' not found in EPG!") %(sstr)), MessageBox.TYPE_INFO, 5)

#---------------------------------------------------------------------------------

class EPGSearchView(WidgetVariableList):
	def __init__(self, session, list, sstr):
		WidgetVariableList.__init__ (self, session, title = _("EPG Search") + " '" + sstr + "'", icon="icon_epgsearch.png")
		self.skinName = [self.__class__.__name__+"0","VariableList2Lines_" + self.__class__.__name__,"VariableList2Lines"]

		self.__epgliste=list
		self.onLayoutFinish.append(self.__fillList)
		
		
	def __checkTimer(self, refstr, eventId):
		for x in self.session.nav.RecordTimer.timer_list:
			if x.service_ref.ref.toString() == refstr:
				if x.eit == eventId:
					return True
		return False

	def __fillList(self):
		list=[]
		for x in self.__epgliste:
			print x
			pix = None
			if self.__checkTimer(x[0],x[1]):
				pix = gLoadPixmap("epgclock.png")
			t = localtime(x[2])
			timestr = "%s %02d.%02d, %02d:%02d"%(dayStrSmall[t[6]],t[2],t[1],t[3],t[4])
			list.append((timestr + "\t" + x[3], x[5], pix, ctoolsclass.getSeperatorPic(), x))

		self.SetList(list)
		self.SetLabel(getEntryString(len(list)))
		
	def KeyOk(self):
		cur = self["menu"].getCurrent()
		if cur and cur[4]:
			print cur[4]
			event = eEPGCache.getInstance().lookupEventId(eServiceReference(cur[4][0]), cur[4][1])

			print event
			if event:
				self.session.openWithCallback(self.__fillList, EventViewSimple, event, ServiceReference(cur[4][0]))#Event, Ref

	def KeyExit(self):
		self.close()
