# -*- coding: utf-8 -*-
from gLocale import _
from GeminiDef import *

from gTools import libgeminimain, cleanexit, getEntryString, monthStr, dayStr, pathRemove
from WidgetVariableList import WidgetVariableList

from Screens.MessageBox import MessageBox
from WidgetConfig import gConfigSelection, gConfigWindow, gConfigOnOff, CONFIGSEPERATOR, gConfigDirectory
from Components.config import config, NoSave, getConfigListEntry, ConfigInteger

from enigma import eTimer

MIN = 0
HOUR = 1
DAY = 2
MON = 3
WDAY = 4
COMM = 5

TIME_SET=0
ALWAYS_SET=1
INTERVAL_SET=2

CRONDCONFIGDIR = "/etc/cron/crontabs"
CRONDCONFIGFILE = "/etc/cron/crontabs/root"
DEFAULTSCRIPT = "/usr/bin/crontest.sh"
CRONSTARTSCRIPT = "/etc/init.d/busybox-cron"

def getStr(list):
	if list[1] == TIME_SET:
		return str(list[0]) + " "
	if list[1] == ALWAYS_SET:
		return "* "
	else:
		return "*/" + str(list[0]) + " "

def getDesc(list):
	text=""
	for x in range(len(list)):
		if x==MIN:
			if list[x][1] == ALWAYS_SET:
				text += _("every minute")
			if list[x][1] == TIME_SET:
				text += _("in %dst minutes") % list[x][0]
			if list[x][1] == INTERVAL_SET:
				text += _("in %d minutes interval") % list[x][0]
			text += ", "
		if x==HOUR:
			if list[x][1] == ALWAYS_SET:
				text += _("every hour")
			if list[x][1] == TIME_SET:
				text += _("by %d clock") % list[x][0]
			if list[x][1] == INTERVAL_SET:
				text += _("in %d hours interval") % list[x][0]
			text += ", "
		if x==DAY:
			if list[x][1] == ALWAYS_SET:
				text += _("every day")
			if list[x][1] == TIME_SET:
				text += _("on %dth day") % list[x][0]
			if list[x][1] == INTERVAL_SET:
				text += _("in %d days interval") % list[x][0]
			text += "\n"
		if x==MON:
			if list[x][1] == ALWAYS_SET:
				text += _("every month")
			if list[x][1] == TIME_SET:
				text += _("in month %s") % _(monthStr[list[x][0]-1])
			text += ", "
		if x==WDAY:
			if list[x][1] == ALWAYS_SET:
				text += _("on any weekday")
			if list[x][1] == TIME_SET:
				text += _("every %s") % _(dayStr[list[x][0]-1])
	return text

def GetCText(x):
	text = "(" + getStr(x[MIN]) + getStr(x[HOUR]) + getStr(x[DAY]) + getStr(x[MON]) + getStr(x[WDAY]) + ")  " + x[COMM]
	text += "\n" + getDesc(x)
	return text

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

class Cron(WidgetVariableList):
	def __init__(self, session, name=None):
		self.newconf=False
		self.cronrunning=False
		from lib import libgtools
		list=[]
		for x in libgtools.getCronInfo(CRONDCONFIGDIR):
			list.append((GetCText(x),None,x))
		del libgtools
			
		WidgetVariableList.__init__ (self, session, name or _("Cron"), LinesProEntry=3, NameRed=_("Delete"), NameGreen=_("Add"), NameBlue=" ", icon="icon_crondconf.png",list=list)
		self.skinName = [self.__class__.__name__,"VariableList3Button_" + self.__class__.__name__,"VariableList3Button"]
		
		self.__clock_timer = eTimer()
		self.__clock_timer_conn = self.__clock_timer.timeout.connect(self.__SetLabel)
		self.__clock_timer.start(300)
	
	def __SetLabel(self):
		text = _("Cron") + " "
		if libgeminimain.isRunning("crond"):
			self.cronrunning=True
			text += _("running")
			self.SetBB()
		else:
			self.cronrunning=False
			text += _("not running")
			if len(self.GetList())>0:
				self.SetBB(_("%s start") %_("Cron"))
		self.SetLabel(text)
		self.__clock_timer.start(3000)

	def KeyOk(self):
		val = self.getCurrentEntry()
		if val and val[2]:
			self.session.openWithCallback(self.__Callbackedit, CrondConfig, val[2])

	def KeyRed(self):
		val = self.getCurrentEntry()
		if val:
			self.RemoveEntry(self.GetIndex())
			self.newconf=True

	def KeyGreen(self):
		self.session.openWithCallback(self.__Callbackappend, CrondConfig)
		
	def KeyBlue(self):
		if self.cronrunning==False:
			libgeminimain.sendDbus("gdaemon",0,CRONSTARTSCRIPT + " start")
			self.session.open(MessageBox, _("Values stored"), MessageBox.TYPE_INFO, 5)
		
	def __Callbackappend(self, res=False):
		if res:
			self.addEntry(res)
			self.newconf=True
			
	def __Callbackedit(self, res = False):
		if res:
			self.editEntry(self.GetIndex(),res)
			self.newconf=True

	def KeyExit(self):
		if self.newconf:
			try:
				if len(self.GetList())<1:
					pathRemove(CRONDCONFIGFILE)
					libgeminimain.sendDbus("gdaemon",0,CRONSTARTSCRIPT + " stop")
				else:
					wfile = open(CRONDCONFIGFILE, 'w')
					for y in self.GetList():
						x = y[2]
						wfile.write("%s%s%s%s%s%s\n" % (getStr(x[MIN]), getStr(x[HOUR]), getStr(x[DAY]), getStr(x[MON]), getStr(x[WDAY]), x[COMM]))
					wfile.close()
					libgeminimain.sendDbus("gdaemon",0,CRONSTARTSCRIPT + " stop")
					libgeminimain.sendDbus("gdaemon",0,CRONSTARTSCRIPT + " start")
				self.session.open(MessageBox, _("Values stored"), MessageBox.TYPE_INFO, 5)
			except:
				pass
		del self.__clock_timer
		self.close()
		cleanexit(__name__)

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

class CrondConfig(gConfigWindow):
	def __init__(self, session, clist=[[0, 0], [1, 2], [1, 1], [1, 1], [1, 1], DEFAULTSCRIPT]):
		gConfigWindow.__init__(self, session, icon="icon_crondconf.png")

		Smenu = [("0", _("Time")), ("1", _("always")), ("2", _("Interval"))]
		#Min
		config.bp.Smin = NoSave(gConfigSelection(default=str(clist[MIN][1]), choices=Smenu))
		config.bp.Vmin = NoSave(ConfigInteger(default=clist[MIN][0], limits=(0, 59)))
		#Hour
		config.bp.Shour = NoSave(gConfigSelection(default=str(clist[HOUR][1]), choices=Smenu))
		config.bp.Vhour = NoSave(ConfigInteger(default=clist[HOUR][0], limits=(0, 23)))
		#Day
		config.bp.Sday = NoSave(gConfigSelection(default=str(clist[DAY][1]), choices=Smenu))
		config.bp.Vday = NoSave(ConfigInteger(default=clist[DAY][0], limits=(1, 31)))
		#Months
		Smenu.pop(2)#cut interval
		Vmenu = []
		for x in range(12):
			Vmenu.append((str(x+1), monthStr[x]))
		config.bp.Smon = NoSave(gConfigSelection(default=str(clist[MON][1]), choices=Smenu))
		config.bp.Vmon = NoSave(gConfigSelection(default=str(clist[MON][0]), choices=Vmenu))
		#Weekday
		Vmenu = []
		for x in range(7):
			Vmenu.append((str(x+1), dayStr[x]))
		config.bp.Swday = NoSave(gConfigSelection(default=str(clist[WDAY][1]), choices=Smenu))
		config.bp.Vwday = NoSave(gConfigSelection(default=str(clist[WDAY][0]), choices=Vmenu))
		#Script
		config.bp.comm = NoSave(gConfigDirectory(default=clist[COMM], filter=FILTER_SCRIPTE))
		
		self.__fillList()
	
	def __fillList(self):
		list = []
		#Min
		list.append(getConfigListEntry(_("Minute(s) as"), config.bp.Smin))
		if config.bp.Smin.value != "1":
			list.append(getConfigListEntry(_("Minute(s)"), config.bp.Vmin))
		list.append(CONFIGSEPERATOR())
		#Hour
		list.append(getConfigListEntry(_("Hour(s) as"), config.bp.Shour))
		if config.bp.Shour.value != "1":
			list.append(getConfigListEntry(_("Hour(s)"), config.bp.Vhour))
		list.append(CONFIGSEPERATOR())
		#Day
		list.append(getConfigListEntry(_("Day(s) as"), config.bp.Sday))
		if config.bp.Sday.value != "1":
			list.append(getConfigListEntry(_("Day(s)"), config.bp.Vday))
		list.append(CONFIGSEPERATOR())
		#Months
		list.append(getConfigListEntry(_("Month as"), config.bp.Smon))
		if config.bp.Smon.value != "1":
			list.append(getConfigListEntry(_("Month"), config.bp.Vmon))
		list.append(CONFIGSEPERATOR())
		#Weekday
		list.append(getConfigListEntry(_("Weekday as"), config.bp.Swday))
		if config.bp.Swday.value != "1":
			list.append(getConfigListEntry(_("Weekday"), config.bp.Vwday))
		list.append(CONFIGSEPERATOR())

		list.append(getConfigListEntry(_("Script"), config.bp.comm))
		self.SetConfList(list)

	def KeyLeft(self):
		gConfigWindow.KeyLeft(self)
		self.__fillList()

	def KeyRight(self):
		gConfigWindow.KeyRight(self)
		self.__fillList()

	def KeyGreen(self):
		list=[]
		list.append([config.bp.Vmin.value, int(config.bp.Smin.value)])
		list.append([config.bp.Vhour.value, int(config.bp.Shour.value)])
		list.append([config.bp.Vday.value, int(config.bp.Sday.value)])
		list.append([int(config.bp.Vmon.value), int(config.bp.Smon.value)])
		list.append([int(config.bp.Vwday.value), int(config.bp.Swday.value)])
		list.append(config.bp.comm.value)
		self.close((GetCText(list),None,list))

	def KeyExit(self):
		self.close()
