from Screen import Screen
import ChannelSelection
from ServiceReference import ServiceReference
from Components.config import config, ConfigSelection, ConfigText, ConfigSubList, ConfigDateTime, ConfigClock, ConfigYesNo, getConfigListEntry
from Components.ActionMap import NumberActionMap
from Components.ConfigList import ConfigListScreen
from Tools.BoundFunction import boundFunction
from Components.MenuList import MenuList
from Components.Sources.StaticText import StaticText
from Components.Label import Label
from Components.NimManager import nimmanager
from Components.SystemInfo import SystemInfo
from Components.UsageConfig import defaultMoviePath
from Screens.MovieSelection import getPreferredTagEditor
from Screens.LocationBox import MovieLocationBox
from Screens.ChoiceBox import ChoiceBox
from Screens.MessageBox import MessageBox
from Screens.VirtualKeyBoard import VirtualKeyBoard
from Tools.Alternatives import GetWithAlternative
from Tools.FallbackTimer import FallbackTimerDirs
from RecordTimer import AFTEREVENT
from enigma import eEPGCache, iRecordableServicePtr
from time import localtime, mktime, time, strftime
from datetime import datetime
import urllib

class TimerEntry(Screen, ConfigListScreen):
	def __init__(self, session, timer):
		Screen.__init__(self, session)
		self.timer = timer

		self.timer.service_ref_prev = self.timer.service_ref
		self.timer.begin_prev = self.timer.begin
		self.timer.end_prev = self.timer.end
		self.timer.external_prev = self.timer.external
		self.timer.dirname_prev = self.timer.dirname

		self.entryDate = None
		self.entrySe
rvice = None

		self["key_red"] = StaticText(_("Cancel"))
		self["key_green"] = StaticText(_("Save"))
		self["key_yellow"] = StaticText(_("Timer type"))
		self["key_blue"] = StaticText("")

		self["actions"] = NumberActionMap(["SetupActions", "GlobalActions", "PiPSetupActions", "ColorActions"],
		{
			"ok": self.keySelect,
			"save": self.keyGo,
			"cancel": self.keyCancel,
			"volumeUp": self.incrementStart,
			"volumeDown"
: self.decrementStart,
			"size+": self.incrementEnd,
			"size-": self.decrementEnd,
			"red": self.keyCancel,
			"green": self.keyGo,
			"yellow": self.changeTimerType,
			"blue": self.changeZapWakeupType
		}, -2)

		self.list = []

		ConfigListScreen.__init__(self, self.list, session = session)
		self.setTitle(_("Timer entry"))
		FallbackTimerDirs(self, self.createConfig)

	def createConfig(self, currlocation=None, locations=[]):
		justplay = self.timer.justplay
		always_zap = self.timer.always_zap
		zap_wakeup = self.timer.zap_wakeup
		pipzap = self.timer.pipzap
		rename_repeat = self.timer.rename_repeat
		conflict_detection = self.timer.conflict_detection

		afterevent = {
			AFTEREVENT.NONE: "nothing",
			AFTEREVENT.DEEPSTANDBY: "deepstandby",
			AFTEREVENT.STANDBY: "standby",
			AFTEREVENT.AUTO: "auto"
			}[self.timer.afterEvent]

		if self.timer.record_ecm and self.timer.descramble:
			recordingtype = "descrambled+ecm"
		elif self.timer.record_ecm:
			recordingtype = "scrambled+ecm"
		elif self.timer.descramble:
			recordingtype = "normal"

		weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")

		day = list([int(x) for x in reversed('{0:07b}'.format(self.timer.repeated))])
		weekday = 0
		if self.timer.repeated: # repeated
			type = "repeated"
			if (self.timer.repeated == 31): # Mon-Fri
				repeated = "weekdays"
			elif (self.timer.repeated == 127): # daily
				repeated = "daily"
			else:
				repeated = "user"
				if day.count(1) == 1:
					repeated = "weekly"
					weekday = day.index(1)
		else: # once
			type = "once"
			repeated = None
			weekday = int(strftime("%u", localtime(self.timer.begin))) - 1
			day[weekday] = 1
		self.timerentry_fallback = ConfigYesNo(default=self.timer.external_prev or config.usage.remote_fallback_external_timer.value and config.usage.remote_fallback.value and not nimmanager.somethingConnected())
		self.timerentry_justplay = ConfigSelection(choices = [
			("zap", _("zap")), ("record", _("record")), ("zap+record", _("zap and record"))],
			default = {0: "record", 1: "zap", 2: "zap+record"}[justplay + 2*always_zap])
		if SystemInfo["DeepstandbySupport"]:
			shutdownString = _("go to deep standby")
			choicelist = [("always", _("always")), ("from_standby", _("only from standby")), ("from_deep_standby", _("only from deep standby")), ("never", _("never"))]
		else:
			shutdownString = _("shut down")
			choicelist = [("always", _("always")), ("never", _("never"))]
		self.timerentry_zapwakeup = ConfigSelection(choices = choicelist, default = zap_wakeup)
		self.timerentry_afterevent = ConfigSelection(choices = [("nothing", _("do nothing")), ("standby", _("go to standby")), ("deepstandby", shutdownString), ("auto", _("auto"))], default = afterevent)
		self.timerentry_recordingtype = ConfigSelection(choices = [("normal", _("normal")), ("descrambled+ecm", _("descramble and record ecm")), ("scrambled+ecm", _("don't descramble, record ecm"))], default = recordingtype)
		self.timerentry_type = ConfigSelection(choices = [("once",_("once")), ("repeated", _("repeated"))], default = type)
		self.timerentry_name = ConfigText(default = self.timer.name, visible_width = 50, fixed_size = False)
		self.timerentry_description = ConfigText(default = self.timer.description, visible_width = 50, fixed_size = False)
		self.timerentry_tags = self.timer.tags[:]
		self.timerentry_tagsset = ConfigSelection(choices = [not self.timerentry_tags and "None" or " ".join(self.timerentry_tags)])

		self.timerentry_repeated = ConfigSelection(default = repeated, choices = [("weekly", _("weekly")), ("daily", _("daily")), ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])
		self.timerentry_renamerepeat = ConfigYesNo(default = rename_repeat)
		self.timerentry_pipzap = ConfigYesNo(default = pipzap)
		self.timerentry_conflictdetection = ConfigYesNo(default = conflict_detection)

		self.timerentry_date = ConfigDateTime(default = self.timer.begin, formatstring = _("%d.%B %Y"), increment = 86400)
		self.timerentry_starttime = ConfigClock(default = self.timer.begin)
		self.timerentry_endtime = ConfigClock(default = self.timer.end)
		self.timerentry_showendtime = ConfigSelection(default = ((self.timer.end - self.timer.begin) > 4), choices = [(True, _("yes")), (False, _("no"))])

		default = not self.timer.external_prev and self.timer.dirname or defaultMoviePath()
		tmp = config.movielist.videodirs.value
		if default not in tmp:
			tmp.append(default)
		self.timerentry_dirname = ConfigSelection(default = default, choices = tmp)

		default = self.timer.external_prev and self.timer.dirname or currlocation
		if default not in locations:
			locations.append(default)
		self.timerentry_fallbackdirname = ConfigSelection(default=default, choices=locations)

		self.timerentry_repeatedbegindate = ConfigDateTime(default = self.timer.repeatedbegindate, formatstring = _("%d.%B %Y"), increment = 86400)

		self.timerentry_weekday = ConfigSelection(default = weekday_table[weekday], choices = [("mon",_("Monday")), ("tue", _("Tuesday")), ("wed",_("Wednesday")), ("thu", _("Thursday")), ("fri", _("Friday")), ("sat", _("Saturday")), ("sun", _("Sunday"))])

		self.timerentry_day = ConfigSubList()
		for x in (0, 1, 2, 3, 4, 5, 6):
			self.timerentry_day.append(ConfigYesNo(default = day[x]))

		# FIXME some service-chooser needed here
		servicename = "N/A"
		try: # no current service available?
			servicename = str(self.timer.service_ref.getServiceName())
		except:
			pass
		self.timerentry_service_ref = self.timer.service_ref
		self.timerentry_service = ConfigSelection([servicename])
		self.createSetup("config")

	def createSetup(self, widget):
		self.list = []
		self.entryFallbackTimer = getConfigListEntry(_("Fallback Timer"), self.timerentry_fallback)
		if config.usage.remote_fallback_external_timer.value and config.usage.remote_fallback.value and not hasattr(self, "timerentry_remote"):
			self.list.append(self.entryFallbackTimer)
		self.entryName = getConfigListEntry(_("Name"), self.timerentry_name)
		self.list.append(self.entryName)
		self.entryDescription = getConfigListEntry(_("Description"), self.timerentry_description)
		self.list.append(self.entryDescription)
	