# -*- coding: utf-8 -*-
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
import os

userscripts_version = "1.2"
userscripts_plugindir="/usr/lib/enigma2/python/Plugins/Extensions/SA-KeyUpdater" 
userscripts_path = "/usr/lib/enigma2/python/Plugins/Extensions/SA-KeyUpdater/script"
userscripts_readme = "%s/readme.txt" % userscripts_plugindir

def main(session,**kwargs):
    session.open(UserScriptsPlugin)

def autostart(reason,**kwargs):
    if reason == 0:
        print "[USERSCRIPTS] no autostart"

def Plugins(**kwargs):
    return [PluginDescriptor(name="SatAngels-IPBox-KeyUpdater 1.2", description=_("SatAngels Online KeyUpdate"), where = PluginDescriptor.WHERE_PLUGINMENU, icon="satangels.png", fnc=main),
			PluginDescriptor(name="SatAngels-IPBox-KeyUpdater 1.2", description=_("SatAngels Online KeyUpdate"), where = PluginDescriptor.WHERE_EXTENSIONSMENU, icon="satangels.png", fnc=main)]

class UserScriptsPlugin(Screen):
    skin = """
        <screen position="150,100" size="500,200" title="SatAngels IPBox Script Menu" >
            <widget name="menu" position="10,10" size="390,190" scrollbarMode="showOnDemand" />
        </screen>"""
        
    def __init__(self, session, args = 0):
        self.skin = UserScriptsPlugin.skin
        self.session = session
        Screen.__init__(self, session)
        self.menu = args
        userscriptlist = []
        userscriptlist.append((_("SatAngels IPBox KeyUpdate Scripts 1.2"), "userscripts"))
        userscriptlist.append((_("SatAngels Readme"), "readmeuserscripts"))        
        userscriptlist.append((_("about SatAngels IPBox KeyUpdater %s") % userscripts_version, "aboutuserscripts"))        
        self["menu"] = MenuList(userscriptlist)
        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 "userscripts":
              UserScripts(self.session)
           elif returnValue is "readmeuserscripts":
              self.session.open(Console,_("Scripts readme.txt"),["cat %s" % userscripts_readme])
           elif returnValue is "aboutuserscripts":
              title=_("SatAngels-IPBox-KeyUpdater %s from 05-06-2009\n\nby redbull301") % (userscripts_version)
              self.session.open(MessageBox, title,  MessageBox.TYPE_INFO)

class UserScripts(Screen):
    def __init__(self, session):
        self.session = session
        self.session.openWithCallback(self.askForUserScripts,ChoiceBox,_("select Script"),self.getUserScriptsList())

    def askForUserScripts(self,script):
        if script is None:
            self.skipUserScripts(_("no script selected"))
        else:
            self.userscript=script[1]
            self.session.openWithCallback(self.askForScriptsOption,ChoiceBox,_("select Script option"),self.getUserScriptsOptionList())
            
    def askForScriptsOption(self,option):
        if option is None:
            self.skipUserScripts(_("no option passed"))
        else:
            self.userscript_option = option[1].rstrip()
            if self.userscript_option == "userdefined":
	       self.session.openWithCallback(self.UserScriptsOption,InputBox, title=_("Please enter option for %s") % self.userscript, text="restart                              ", maxSize=35, type=Input.TEXT)
            else:
               self.session.openWithCallback(self.UserScriptExecution,MessageBox,_("are you sure to %s %s?") %(self.userscript_option,self.userscript), MessageBox.TYPE_YESNO)

    def UserScriptsOption(self,option):
        if option is None:
            self.skipUserScripts(_("option is none"))
        else:
            self.userscript_option = option.rstrip()
            self.session.openWithCallback(self.UserScriptExecution,MessageBox,_("are you sure to %s %s ?") % (self.userscript_option, self.userscript), MessageBox.TYPE_YESNO)
            
    def UserScriptExecution(self,answer):
        if answer is None:
            self.skipUserScripts(_("answer is None"))
        if answer is False:
            self.skipUserScripts(_("you were not confirming"))
        else:
            title = _("%s executing Script %s" %(self.userscript_option,self.userscript))
            cmd = "%s/%s %s"  % (userscripts_path,self.userscript,self.userscript_option)
            self.session.open(Console,_(title),[cmd])
            
    def skipUserScripts(self,reason):
        self.session.open(MessageBox,_("Script was canceled, because %s") % reason, MessageBox.TYPE_ERROR)

    def getUserScriptsList(self):
        userscripts = []
        if os.path.exists(userscripts_path) is True:
           for script in os.listdir(userscripts_path):
              if script.startswith(".") is False: 
                 userscripts.append(( script, script ))
        return userscripts

    def getUserScriptsOptionList(self):
        userscripts_option = []  
	userscripts_option.append(( "start", "start" ))

        
#       add further option here
#       userscripts_option.append(( "dummy", "dummy" ))
        return userscripts_option



