#
# abbonamento plugin by @Tiger Team
#
from enigma import *
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Screens.InputBox import InputBox
from Screens.ChoiceBox import ChoiceBox
from Components.ActionMap import ActionMap, NumberActionMap
from Components.ScrollLabel import ScrollLabel
from Components.GUIComponent import *
from Components.MenuList import MenuList
from Components.Input import Input
from Screens.Console import Console
from Plugins.Plugin import PluginDescriptor
#from Screens.ImageWizard import ImageWizard
from Plugins.Plugin import PluginDescriptor

import os

abbonamento_readme = "/usr/lib/enigma2/python/Plugins/Extensions/Abbonamento/Stato.txt"
abbonamento_readme2 = "/usr/lib/enigma2/python/Plugins/Extensions/Abbonamento/server.txt"

# versionstring
abbonamento_pluginversion = "2.3"

def main(session,**kwargs):
    try:    
     	session.open(Abbonamento)
    except:
        print "[ABBONAMENTO] Pluginexecution failed"

def autostart(reason,**kwargs):
    if reason == 0:
        print "[ABBONAMENTO] no autostart"

def Plugins(**kwargs):
    return PluginDescriptor(
        name=_("Abbonamento"), 
        description=_("Stato di Abbonamento - By @Tiger Team"), 
        where = PluginDescriptor.WHERE_PLUGINMENU,
        icon = "abbonamento.png",
        fnc = main
        )

class Abbonamento(Screen):
    skin = """
        <screen position="center,center" size="600,500" title="Abbonamento">
            <widget name="menu" position="10,10" size="490,390" scrollbarMode="showOnDemand" />
        </screen>""" 
        
    def __init__(self, session, args = 0):
        self.skin = Abbonamento.skin
        self.session = session
        Screen.__init__(self, session)
        self.menu = args
        list = []
        list.append((_("Stato di Abbonamento"), "readme"))        
        list.append((_("Stato del Server"), "readme2"))
        self["menu"] = MenuList(list)
        self["actions"] = ActionMap(["WizardActions", "DirectionActions"],{"ok": self.go,"back": self.close,}, -1)
        
    def go(self):
        returnValue = self["menu"].l.getCurrentSelection()[1]
        if returnValue is not None:
           if returnValue is "addwizzard":
               AddCommandWizzard(self.session)
           elif returnValue is "laterwizzard":
               LaterCommandWizzard(self.session)
           elif returnValue is "list":
             self.session.open(Console,_("Listing crontab"),["%s list" % abbonamento_script])
           elif returnValue is "delete":
             self.session.open(Console,_("Deleting crontab"),["%s delete" % abbonamento_script])
           elif returnValue is "reload":
             self.session.open(Console,_("Reloading crontab"),["%s reload" % abbonamento_script])
           elif returnValue is "info":
             self.session.open(Console,_("showing Abbonamento Info"),["%s info" % abbonamento_script])
           elif returnValue is "time":
             self.session.open(Console,_("showing system time "),["%s time" % abbonamento_script])
           elif returnValue is "changetime":
               ChangeTimeWizzard(self.session)
           elif returnValue is "restartwizzard":
               RestartWizzard(self.session)
           elif returnValue is "readme":
             self.session.open(Console,_("Stato di Abbonamento"),["cat %s" % abbonamento_readme])
           elif returnValue is "readme2":
             self.session.open(Console,_("Stato Server"),["cat %s" % abbonamento_readme2])
           elif returnValue is "help":
             self.session.open(Console,_("short help on Abbonamento commands"),["%s" % abbonamento_script])
           elif returnValue is "about":
             self.session.open(MessageBox,_("Abbonamento Enigma2 Plugin Version %s by gutemine" % abbonamento_pluginversion), MessageBox.TYPE_INFO)

class AddCommandWizzard(Screen):
    def __init__(self, session):

        self.session = session
        self.askForCommand()

    def askForCommand(self):
	       self.session.openWithCallback(self.processingCommand,InputBox, title=_("Enter a script to execute at time"), text="/etc/cron/examples/rmc.sh 30 8" , maxSize=False, type=Input.TEXT)

    def processingCommand(self,targetname):
        if targetname is None:
            self.skipCommand(_("Script for adding to crontab is NONE, skipping crontab add command"))
        else:
            self.targetname = targetname
            self.session.openWithCallback(self.DoCommand,MessageBox,_("are you sure to add this script to crontab: %s ?" % (self.targetname)), MessageBox.TYPE_YESNO)

    def DoCommand(self,answer):
        if answer is None:
            self.skipCommand(_("answer is None"))
        if answer is False:
            self.skipCommand(_("you were not confirming"))
        else:
            title = _("adding script %s to crontab with time") %(self.targetname)
            cmd = "%s add %s" % (abbonamento_script,self.targetname)
            self.session.open(Console,_(title),[cmd])
            
    def skipCommand(self,reason):
        self.session.open(MessageBox,_("add script to crontab was canceled, because %s") % reason, MessageBox.TYPE_WARNING)
        
class LaterCommandWizzard(Screen):
    def __init__(self, session):

        self.session = session
        self.askForLaterCommand()

    def askForLaterCommand(self):
	       self.session.openWithCallback(self.processingLaterCommand,InputBox, title=_("Enter a script to execute with delay"), text="/etc/cron/examples/slt.sh 60" , maxSize=False, type=Input.TEXT)

    def processingLaterCommand(self,targetname):
        if targetname is None:
            self.skipLaterCommand(_("Script for adding to crontab is NONE, skipping crontab delay command"))
        else:
            self.targetname = targetname
            self.session.openWithCallback(self.DoLaterCommand,MessageBox,_("are you sure to add this script to crontab: %s ?") % self.targetname, MessageBox.TYPE_YESNO)

    def DoLaterCommand(self,answer):
        if answer is None:
            self.skipLaterCommand(_("answer is None"))
        if answer is False:
            self.skipLaterCommand(_("you were not confirming"))
        else:
            title = _("adding script %s to crontab with delay") %(self.targetname)
            cmd = "%s delay %s" % (abbonamento_script,self.targetname)
            self.session.open(Console,_(title),[cmd])
            
    def skipLaterCommand(self,reason):
        self.session.open(MessageBox,_("delay script to crontab was canceled, because %s") % reason, MessageBox.TYPE_WARNING)
        
class RestartWizzard(Screen):
    def __init__(self, session):
        self.session = session
        self.askForRestart()
        
    def askForRestart(self):
            self.session.openWithCallback(self.askForCommand,ChoiceBox,_("select restart command to be executed"),self.getCommandList())

    def askForCommand(self,source):
        if source is None:
            self.skipRestart(_("no command passed, skipping restart"))
        else:
            self.source = source [1]
            self.session.openWithCallback(self.restartCommand,MessageBox,_("are you sure to %s") % self.source, MessageBox.TYPE_YESNO)
            
    def restartCommand(self,answer):
        if answer is None:
            self.skipRestart(_("answer is None"))
        if answer is False:
            self.skipRestart(_("you were not confirming"))
        else:
            title = _("executing command on Dreambox")
            cmd = "%s %s"  % (abbonamento_script,self.source)
            self.session.open(Console,_(title),[cmd])
            
    def skipRestart(self,reason):
        self.session.open(MessageBox,_("restart was canceled, because %s") % reason, MessageBox.TYPE_WARNING)
        
    def getCommandList(self):
        images = []
        images.append((_("info if cron daemon is running"),"info"))
        images.append((_("start cron daemon"),"start"))
        images.append((_("stop cron daemon"),"stop"))
        images.append((_("restart cron daemon"),"restart"))
        images.append((_("reboot Dreambox"),"reboot"))
        images.append((_("halt Dreambox"),"halt"))
        images.append((_("restart Enigma on Dreambox"),"kill"))
        return images


