# -*- coding: utf-8 -*-
from gLocale import _
from gTools import cleanexit, HIDETIMERSTRING
from WidgetVariableList import WidgetVariableList
from plugin import cgevent

from WidgetConfig import gConfigWindow, gConfigOnOff
from Components.config import config, NoSave, getConfigListEntry, ConfigClock, ConfigInteger

from Tools.FuzzyDate import FuzzyTime
from Screens.ChannelSelection import SimpleChannelSelection
from ServiceReference import ServiceReference
from RecordTimer import RecordTimerEntry, AFTEREVENT
from Components.TimerSanityCheck import TimerSanityCheck

from datetime import datetime
from time import localtime, mktime

def getTimestamp(Start):
	try:
		d = localtime()
		dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, Start / 100 , Start % 100)
		return int(mktime(dt.timetuple()))
	except:
		return 0
		

class EPGRefresh(WidgetVariableList):
	def __init__(self, session, name=None):
		WidgetVariableList.__init__ (self, session, name or (_("EPG Refresh") + " (G3)"), NameRed=_("Delete"), NameGreen=_("Add"), NameBlue=_("Setup"), icon="icon_epgrefresh.png")
		self.skinName = [self.__class__.__name__,"VariableList3Button_" + self.__class__.__name__,"VariableList3Button"]

		self.__getConfig()
		self.onLayoutFinish.append(self.__fillList)

	def __getConfig(self):
		self.__epgStart = getTimestamp(cgevent.getConfig("epg_start",500))
		self.__interval = cgevent.getConfig("epg_interval",4)
		self.__activ = cgevent.getConfig("epg_on",0)

	def __fillList(self):
		list=[]
		for x in self.session.nav.RecordTimer.timer_list + self.session.nav.RecordTimer.processed_timers:
			if x.description==HIDETIMERSTRING and x.name=="EPGRefresh":
				tmpstr =  FuzzyTime(x.begin)[1] + "\t" + x.service_ref.getServiceName()
				list.append((tmpstr,None, x))
		
		list.sort(cmp = lambda x, y: x[2].begin < y[2].begin)
		self.SetList(list)
		
		if self.__activ:
			tmpend = self.__epgStart + (len(list) * self.__interval * 60)
			self.SetLabel(_("Start Time")+ " " + FuzzyTime(self.__epgStart)[1] + "    \t" + _("End") + " "+FuzzyTime(tmpend)[1])
		else:
			self.SetLabel(_("Status: stopped"))

	def KeyBlue(self):
		self.session.openWithCallback(self.__CallbackConfig, EpgRefreshSetup, self.__activ, self.__epgStart, self.__interval)

	def KeyGreen(self):
		self.session.openWithCallback(self.__finishedChannelSelection, SimpleChannelSelection," ")
		
	def KeyRed(self):
		val = self.getCurrentEntry()
		if val:
			#timer = val[2]
			#timer.afterEvent = AFTEREVENT.NONE
			self.session.nav.RecordTimer.removeEntry(val[2])
			self.__fillList()
			self.__ChangedEntry()
			self.__fillList()
	
	def __ChangedEntry(self):
		count = 0
		for x in self.GetList():
			if x[2].description==HIDETIMERSTRING and x[2].name=="EPGRefresh":
				x[2].begin = self.__epgStart + (count * self.__interval *60)
				x[2].end = self.__epgStart + (count * self.__interval *60) + 1
				if self.__activ:
					x[2].enable()
				else:
					x[2].disable()
				self.session.nav.RecordTimer.timeChanged(x[2])
				count += 1
	
	def __CallbackConfig(self, val=False):
		if val:
			self.__getConfig()
			self.__ChangedEntry()
			self.__fillList()

	def __finishedChannelSelection(self, *args):
		if len(args):
			serviceref = ServiceReference(args[0])
			disabled = True
			if self.__activ:
				disabled = False
			time_val = self.__epgStart + (len(self.GetList()) * self.__interval * 60)
			self.__addTimer(RecordTimerEntry(serviceref, time_val, time_val + 1, "EPGRefresh", HIDETIMERSTRING, eit=None, disabled=disabled, justplay=True, afterEvent=AFTEREVENT.STANDBY, checkOldTimers=True))
		
	def __addTimer(self, timer):
		timersanitycheck = TimerSanityCheck(self.session.nav.RecordTimer.timer_list, timer)
		if not timersanitycheck.check():
			self.session.open(MessageBox, _("Conflicting timer"), MessageBox.TYPE_ERROR)
		else:
			for x in range(0,7):
				timer.setRepeated(x)
			self.session.nav.RecordTimer.record(timer)
			self.__fillList()

	def KeyExit(self):
		self.close()
		cleanexit(__name__)

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

class EpgRefreshSetup(gConfigWindow):
	def __init__(self, session, activ, epgStart, interval):

		list = []
		config.bp.onoff = NoSave(gConfigOnOff(default=activ))
		config.bp.start = NoSave(ConfigClock(default = epgStart))
		config.bp.interval = NoSave(ConfigInteger(default=interval,limits=(2, 30)))
		
		list.append(getConfigListEntry(_("EPG Refresh"), config.bp.onoff))
		list.append(getConfigListEntry(_("Start Time"), config.bp.start))
		list.append(getConfigListEntry(_("Duration") + " " + _("(in Min.)"), config.bp.interval))
		gConfigWindow.__init__(self, session, list=list, icon="icon_epgrefresh.png")
	
	def KeyGreen(self):
		cgevent.setConfig("epg_on", config.bp.onoff.value)
		cgevent.setConfig("epg_start", (config.bp.start.value[0]*100) + config.bp.start.value[1])
		cgevent.setConfig("epg_interval", config.bp.interval.value)
		self.close(True)
	
	def KeyExit(self):
		self.close()
		