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

from Components.TimerSanityCheck import TimerSanityCheck
from RecordTimer import RecordTimerEntry, AFTEREVENT
from ServiceReference import ServiceReference
from Components.ActionMap import ActionMap
from Components.Label import Label
from Screens.Screen import Screen

from time import time as os_time

class ReZapp(Screen):
	def __init__(self, session):
		print "uff"
		Screen.__init__(self, session)
		self.skinName = [self.__class__.__name__]
		self["actions"] = ActionMap(["gActions"],
		{
			"exit": self.KeyExit,
			"left": self.keyLeft,
			"right": self.keyRight,
			"ok": self.KeyOk
		}, -1)

		ch_name = _("not found")
		self.oldServiceRef = ServiceReference(self.session.nav.getCurrentlyPlayingServiceReference())
		if self.oldServiceRef is not None:
			ch_name = self.oldServiceRef.getServiceName()

		self.zapptime = cgevent.getConfig("ReZapptime",5)

		self["ll"] = Label("<")
		self["rr"] = Label(">")
		self["label0"] = Label(ch_name)
		self["label1"] = Label("%d min" %self.zapptime)
		self["label2"] = Label(_("Press OK to save settings."))
		
		for x in self.session.nav.RecordTimer.timer_list:
			if x.description == HIDETIMERSTRING and x.name=="ReZapp":
				print "remove old ReZappTimer"
				self.session.nav.RecordTimer.removeEntry(x)
				
	def KeyExit(self):
		self.close(None)
		cleanexit(__name__)

	def keyRight(self):
		self.zapptime += 1
		if self.zapptime > 99:
			self.zapptime = 99
		self["label1"].setText("%d min" %self.zapptime)

	def keyLeft(self):
		self.zapptime -= 1
		if self.zapptime < 1:
			self.zapptime = 1
		self["label1"].setText("%d min" %self.zapptime)

	def KeyOk(self):
		if self.oldServiceRef is not None:
			begin = int(os_time()) + (self.zapptime *60)
			self.__addTimer(RecordTimerEntry(self.oldServiceRef, begin, begin + 1, "ReZapp", HIDETIMERSTRING, None, False, True, checkOldTimers = True))
		
	def __addTimer(self, timer):
		timersanitycheck = TimerSanityCheck(self.session.nav.RecordTimer.timer_list, timer)
		if not timersanitycheck.check():
			from Screens.MessageBox import MessageBox
			self.session.open(MessageBox, _("Conflicting timer"), MessageBox.TYPE_INFO)
		else:
			print "Sanity check passed"
			self.session.nav.RecordTimer.record(timer)
			cgevent.setConfig("ReZapptime", self.zapptime)
			self.KeyExit()
