#
# Menu Fantastic Plugin by gutemine
#

from enigma import *
from Screens.Screen import Screen
from Screens.Standby import *
from Screens.MessageBox import MessageBox
from Screens.InputBox import InputBox
from Screens.ChoiceBox import ChoiceBox
from Components.ActionMap import ActionMap, NumberActionMap
from Components.ActionMap import HelpableActionMap
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 RecordTimer import *
from time import *
import os
from Tools import Directories, Notifications
import NavigationInstance
from Components.Button import Button


from Components.Label import Label
from Components.Pixmap import Pixmap
from Components.Sources.Boolean import Boolean
from Components.config import config, ConfigBoolean, ConfigClock
from Components.SystemInfo import SystemInfo
from Screens.Dish import Dish
from Screens.MinuteInput import MinuteInput


# plugin calling support comes here ...

pluginpath = "/usr/lib/enigma2/python/Plugins/"

from Screens.Ci import *

#PluginBrowser
from Screens.PluginBrowser import *
#Network
from Screens.NetworkSetup import *
#LanguageSelection
from Screens.LanguageSelection import *
#ClockDisplay
#from Screens.ClockDisplay import *
#SleepTimer
from Screens.SleepTimerEdit import *



  
########
if os.path.exists("%s/SystemPlugins/Videomode" %pluginpath) is True:
  try:
     from Plugins.SystemPlugins.Videomode.plugin import *
  except:
     pass
########   
 
   
fantastic_pluginversion = "EMUmanager Version 1.0.1"
fantastic_pluginpath = "/usr/lib/enigma2/python/Plugins/Extensions/EMUmanager"
fantastic_readme = "/usr/lib/enigma2/python/Plugins/Extensions/EMUmanager/readme.txt"
splitchar = ":"


session = None


def autostart(reason, **kwargs):
    global session
    if reason == 0 and kwargs.has_key("session"):
       session = kwargs["session"]
       session.open(FantasticBoot)
       
def Plugins(**kwargs):
#    try:
	return [PluginDescriptor(where = [PluginDescriptor.WHERE_SESSIONSTART, PluginDescriptor.WHERE_AUTOSTART], fnc = autostart),

			PluginDescriptor(name="Emu Manager", description="Emu Manager", where = PluginDescriptor.WHERE_EXTENSIONSMENU, icon="fantastic.png", fnc=main)]
#    except:
#	return [PluginDescriptor(where = [PluginDescriptor.WHERE_SESSIONSTART, PluginDescriptor.WHERE_AUTOSTART], fnc = autostart),PluginDescriptor(name="Fantastic", description="Menu Fantastic Plugin", where = PluginDescriptor.WHERE_PLUGINMENU, icon="fantastic.png", fnc=main)]



def main(session,**kwargs):
    try:    
     	session.open(Fantastic)
    except:
        print "[FANTASTIC] Pluginexecution failed"

from Tools.BoundFunction import boundFunction
from Components.PluginComponent import plugins

class Fantastic(Screen):
    EXTENSION_SINGLE = 0
    EXTENSION_LIST = 1


    skin = """
        <screen position="100,100" size="500,400" title="Mbox Menu" >
            <widget name="menu" position="10,10" size="490,390" scrollbarMode="showOnDemand" />
        </screen>"""
# -------------------------------------------
    skinPKT = """
        <screen position="100,100" size="500,400" title="Mbox Menu" >
            <widget name="menu" position="10,10" size="490,390" scrollbarMode="showOnDemand" />
        </screen>"""
# ------------------------------------------

    skinPKTButton = """
        <screen position="80,120" size="560,410" title="Emu Manager" >
		    <ePixmap pixmap="/usr/lib/enigma2/python/Plugins/Extensions/EMUmanager/sf.png" position="80,1" size="404,46" alphatest="on" />
            <eLabel text="_________________________________________________________________________" position="10,30" size="540,25" font="Regular;20" transparent="1" />
            <widget name="menu" position="10,60" size="550,390" scrollbarMode="showOnDemand" />
            <eLabel text="_________________________________________________________________________" position="10,350" size="540,25" font="Regular;20" transparent="1" />
            <eLabel text="Enigma 2 - Tideglo " position="165,382" size="500,25" font="Regular;20" transparent="1" />
        </screen>"""

        
    def __init__(self, session, args = 0):

        self.menu = args
        self.skin = Fantastic.skinPKTButton
        self.session = session
        Screen.__init__(self, session)
        
 #------------------------------------------------------------------------------      
        global mfcommand
        global mfmenu
        global mfmenuold
        global mfexecute
        global mfmenudescr
        global mfintargument
        global mftextargument
        global servicelist
        global pluginlist
        global videomode

#----------------------------------------------------------------------------------------------------
        mfmenu="main"
        mfmenuold="main"
        mfmenudescr="Emu Manager"

  

        mfexecute=" "
        mfintargument=0
        mftextargument=" "
                
        mainmenu = []

        menufile = "%s/%s.cfg" % (fantastic_pluginpath,mfmenu)
        if os.path.exists(menufile) is True:
           mf = open(menufile,"r")
           for line in mf:
              parts=line.split(splitchar,3)
              index=len(parts)
   
              if index > 1:
                 command=parts[0].upper().rstrip()
                 mfcommand=command[0]
                 if mfcommand is not "S":
                    if index >2:
                       mainmenu.append(( str(parts[2]), line ))
                    else:
                       mainmenu.append(( str(parts[1]), line ))
 
           mf.close()
        else:
           mainmenu.append(("no %s.cfg found - select for details" %mfmenu, "mfnomenu")) 
# -----------------------------------              
        if mfmenudescr == "Emu Manager":
          pass
        else:  
# ---------------------------------------------------	dopisac klawisze
          mainmenu.append(("Show readme.txt", "mfreadme"))        
          mainmenu.append(("about %s" %fantastic_pluginversion , "mfabout"))        
        pluginlist="False"
        videomode="1"
        self.list = []
        self["key_green"] = Button("Video Mode")
        self["key_red"] = Button("Media Player")
        self["key_yellow"] = Button("SleepTimer")
        self["key_blue"] = Button("Extensions")
        
        self["menu"] = MenuList(mainmenu)
        self["actions"] = ActionMap(["pktActions", "WizardActions", "DirectionActions"],{"mplayer": self.setMediaPlayer,"videomode": self.setVideoMode,"sleeptimer": self.setSleepTimer,"extensions": self.showExtensionSelection,"ok": self.FantasticMainMenu,"back": self.close,}, -1)
        
    def setSleepTimer(self):
        self.session.open(SleepTimerEdit)
    def setMediaPlayer(self):
        self.session.open(MediaPlayer)

    
    def setVideoMode(self):
        #self.session.openWithCallback(self.FantasticMenu(""),VideoWizard)   
        from enigma import eAVSwitch
        from Screens.MessageBox import MessageBox
        global aspect
        global videomode
        aspect = "16:9"
        if aspect == "16:9":
          if videomode == "1":
            eAVSwitch.getInstance().setAspectRatio(2)
            session.open(MessageBox, _("NonLinear"), type=MessageBox.TYPE_INFO, timeout=2)
            videomode = "2"
          elif videomode == "2": 
            eAVSwitch.getInstance().setAspectRatio(3)
       	    session.open(MessageBox, _("Pan&Scan"), type=MessageBox.TYPE_INFO, timeout=2)
            videomode = "3"
          elif videomode == "3":
            eAVSwitch.getInstance().setAspectRatio(4)
       	    session.open(MessageBox, _("Pillarbox"), type=MessageBox.TYPE_INFO, timeout=2)
            videomode = "4"
          elif videomode == "4":
            eAVSwitch.getInstance().setAspectRatio(1)
       	    session.open(MessageBox, _("JustScale"), type=MessageBox.TYPE_INFO, timeout=2)
            videomode = "1"

           
    def FantasticMainMenu(self):

        global mfcommand
        global mfmenu
        global mfmenuold
        global mfexecute
        global mfmenudescr
        global mfintargument
        global mftextargument

        mfselected = self["menu"].l.getCurrentSelection()[1]

        if mfselected is not None:
           if mfselected is "mfreadme":
                self.session.open(Console,_("Showing Fantastic readme.txt"),["cat %s" % fantastic_readme])
           elif mfselected is "mfnomenu":
               title1=_("Menu Fantastic Plugin") 
               title2=_("needs a %s.cfg file at" % mfmenu)
               title3=_("%s" %fantastic_pluginpath)
               title="%s\n%s\n%s" % (title1, title2,title3)
               self.session.open(MessageBox,("%s") % (title),  MessageBox.TYPE_INFO)
           elif mfselected is "mfabout":
               title1=_("Menu Fantastic Plugin %s") % fantastic_pluginversion
               title2=_("by gutemine is Freeware - use at your own risk !")
               title="%s\n%s" % (title1, title2)
               self.session.open(MessageBox,("%s") % (title),  MessageBox.TYPE_INFO)
           else:
               self.FantasticMenuSelected(mfselected)

    def FantasticMenu(self,status):

        global mfcommand
        global mfmenu
        global mfmenuold
        global mfexecute
        global mfmenudescr
        global mfintargument
        global mftextargument

        if mfmenu is None:
           self.skipMF("No menu passed, returning")
        else:
           mfmenufile = "%s/%s.cfg" % (fantastic_pluginpath,mfmenu.rstrip())
           if os.path.exists(mfmenufile) is True:
              mf = open(mfmenufile,"r")
              line=mf.readline()
              mf.close()
              parts=line.split(splitchar,3)
              index=len(parts)
              if index > 1:
                 command=parts[0].upper().rstrip()
                 # only if menu file contains S in first line startup is executed
                 if command[0] is "S":
                    if index > 3:
                       cmd=parts[3].rstrip()
                       if mfmenu == mfmenuold:
                          pass
                       elif mfmenu == "main":
                          pass
                       else:
                          if os.path.exists("%s/%s" %(fantastic_pluginpath,cmd)) is True:
                             os.system("%s/%s %s" % (fantastic_pluginpath,cmd,mftextargument))
                          else:
                             os.system("%s %s" % (cmd,mftextargument))
                       
                       mfmenudescr=parts[2].rstrip()
                    else:
                       if index is 3:
                          mfmenudescr=parts[2].rstrip()
                       else:
                          mfmenudescr=parts[1].rstrip()
                          
           if os.path.exists("%s/%s.cfg" % (fantastic_pluginpath,mfmenu.rstrip())) is True:
              if mfmenu == "main":
                 pass
              else:
                 self.session.openWithCallback(self.FantasticMenuSelected,ChoiceBox,mfmenudescr,self.ListMenuFantastic())        
           else:
              self.skipMF("no Menufile %s.cfg" %mfmenu)

    def FantasticMenuSelected(self,mfselected):

        global mfcommand
        global mfmenu
        global mfmenuold
        global mfexecute
        global mfmenudescr
        global mfintargument
        global mftextargument


        if mfselected is None:
#           self.skipMF("nothing selected")
           mfmenu="main"
        else:
           try:
              parts=mfselected.split(splitchar,4)
           except:
              parts=mfselected[1].split(splitchar,4)

           mfcommand=" "
           mfexecute=" "
           mfintargument=0
           mftextargument=" "

           index=len(parts)
           if index > 1:
              command=parts[0].upper().rstrip()
              mfcommand=command[0]
           else:
              command=" "
              mfcommand=command[0]

           if index > 1:
              mfmenuold=mfmenu
              mfmenu=parts[1].rstrip()

           if index > 2:
              mfmenudescr=parts[2].rstrip()
           else:
              mfmenudescr=parts[1].rstrip()
              
           if index > 3:
              mfexecute=parts[3].rstrip()
              mftextargument=parts[3].rstrip()

           if index > 4:
              mftextargument=parts[4].rstrip()
              try:
                 mfintargument=int(mftextargument)
              except:
                 mfintargument = 0
           elif index == 4:
              mftextargument=parts[3].rstrip()
              try:
                 mfintargument=int(mftextargument)
              except:
                 mfintargument = 0
           else:
              pass

           if mfcommand is "E":
              if os.path.exists("%s/%s" % (fantastic_pluginpath,mfexecute)) is True:
                 os.system("%s/%s %s" % (fantastic_pluginpath,mfexecute,mftextargument))
              else:
                 os.system("%s %s"  % (mfexecute,mftextargument))
              self.session.openWithCallback(self.FantasticMenu,MessageBox,"%s %s was executed !" %(mfexecute,mftextargument), MessageBox.TYPE_INFO, timeout=mfintargument)
# patched by barabas
           elif mfcommand is "U":
              if os.path.exists("%s/%s" % (fantastic_pluginpath,mfexecute)) is True:
                 os.system("%s/%s %s" % (fantastic_pluginpath,mfexecute,mftextargument))
              else:
                 os.system("%s %s"  % (mfexecute,mftextargument))
# patched by GOst4711
              if os.path.exists("%s.reste2" %(mfexecute)) is True:
                 mfintargument = 3
                 self.session.openWithCallback(self.FantasticMenu,MessageBox,"Restarting Enigma2", MessageBox.TYPE_INFO, timeout=5)
                 TryQuitMainloop(self.session,mfintargument)
              else:                     
                 if os.path.exists("%s.txt" %(mfexecute)) is True:
                    menufile="%s.txt" %(mfexecute)
                    mf = open(menufile,"r")
                    mfexecute=mf.readline()
                    mf.close()
                    self.session.openWithCallback(self.FantasticMenu(""),MessageBox,mfexecute, MessageBox.TYPE_INFO, timeout=4)
# -----------                    
              self.FantasticMenu("") 
# ------ ende ------
           elif mfcommand is "#":
              self.FantasticMenu("")                                
           elif mfcommand is "C":
              if os.path.exists("%s/%s" % (fantastic_pluginpath,mfexecute)) is True:
                 self.session.openWithCallback(self.FantasticMenu(""),Console,_("Executing %s %s" %(mfexecute, mftextargument)),["%s/%s %s" % (fantastic_pluginpath,mfexecute,mftextargument) ])
              else:
                 self.session.openWithCallback(self.FantasticMenu(""),Console,_("Executing %s %s" %(mfexecute, mftextargument)),["%s %s" % (mfexecute, mftextargument) ])
           elif mfcommand is "A":
              FantasticApplication(self.session)
              self.FantasticMenu("")
           elif mfcommand is "P":
              plugininstalled=False
              if os.path.exists("%s/Extensions/%s" %(pluginpath,mftextargument)) is True:
                 plugininstalled=True
              if os.path.exists("%s/SystemPlugins/%s" %(pluginpath,mftextargument)) is True:
                 plugininstalled=True
                               
              if plugininstalled is True:
                 if mftextargument == "Tuxtxt":
                    self.session.openWithCallback(self.FantasticMenu(""),ShellStarter)
                 elif mftextargument == "Multiboot":
                    self.session.openWithCallback(self.FantasticMenu(""),Multiboot)
                 elif mftextargument == "MediaPlayer":
                    self.session.openWithCallback(self.FantasticMenu(""),MediaPlayer)                                     
                 elif mftextargument == "SpiderFan":
                    self.session.openWithCallback(self.FantasticMenu(""),SpiderFan)
                 elif mftextargument == "Shell":
                    self.session.openWithCallback(self.FantasticMenu(""),Shell)
                 elif mftextargument == "PicturePlayer":
                    self.session.openWithCallback(self.FantasticMenu(""),picmain)
                 elif mftextargument == "MOUNTmanager":
                    self.session.openWithCallback(self.FantasticMenu(""),Mountman)
                 elif mftextargument == "ConfigurationBackup":
                    try:
                       self.session.openWithCallback(self.FantasticMenu(""),BackupSetup)
                    except:
                       pass  
		 elif mftextargument == "GboxSuite":
                    try:
                       self.session.openWithCallback(self.FantasticMenu(""),GboxSuite)
                    except:
                       pass  
		 elif mftextargument == "KeyUpdater":
                    try:
                       self.session.openWithCallback(self.FantasticMenu(""),KeyUpdater)
                    except:
                       pass  
		 elif mftextargument == "CCcamInfo":
                    try:
                       self.session.openWithCallback(self.FantasticMenu(""),CCcamInfo)
                    except:
                       pass  
		 elif mftextargument == "LasMail":
                    self.session.openWithCallback(self.FantasticMenu(""),LasMail)	
                 elif mftextargument == "Tuxcom":
                    self.session.openWithCallback(self.FantasticMenu(""),TuxComStarter)
                 elif mftextargument == "Cronmanager":
                    self.session.openWithCallback(self.FantasticMenu(""),Cronmanager)
                 elif mftextargument == "TuxboxGames":
                    self.session.openWithCallback(self.FantasticMenu(""),GameStarter)
                 elif mftextargument == "FrontprocessorUpgrade":
                    self.session.openWithCallback(self.FantasticMenu(""),FPUpgrade)
                 elif mftextargument == "SoftwareUpdate":
                   self.session.openWithCallback(self.FantasticMenu(""),UpdatePluginMenu)
                 elif mftextargument == "weinbergtagger":
                   self.session.openWithCallback(self.FantasticMenu(""),weinbergtagger)
                 elif mftextargument == "SkinSelector":
                    try:
                       self.session.openWithCallback(self.FantasticMenu(""),SkinSelector)
                    except:
                       self.session.openWithCallback(self.FantasticMenu,MessageBox,"Plugin %s is not wrapped !" %mftextargument, MessageBox.TYPE_INFO)
                 else:
                    self.session.openWithCallback(self.FantasticMenu,MessageBox,"Plugin %s is not wrapped !" %mftextargument, MessageBox.TYPE_INFO)
              else:
                 if mftextargument == "Ci":
                    self.session.openWithCallback(self.FantasticMenu(""),CiSelection)
                 elif mftextargument == "PluginBrowser":
                    self.session.openWithCallback(self.FantasticMenu(""),PluginBrowser)      
                 elif mftextargument == "NetworkSetup":
                    self.session.openWithCallback(self.FantasticMenu(""),NetworkAdapterSelection)
                 elif mftextargument == "LanguageSelection":
                    self.session.openWithCallback(self.FantasticMenu(""),LanguageSelection)
#                 elif mftextargument == "ClockDisplay":
#                    self.session.openWithCallback(self.FantasticMenu(""),ClockDisplay)
                 elif mftextargument == "SleepTimerEdit":
                    self.session.openWithCallback(self.FantasticMenu(""),SleepTimerEdit)
                 elif mftextargument == "BP":
                    if os.path.exists("/usr/lib/enigma2/python/Bp") is True:
                       try:
                          self.session.openWithCallback(self.FantasticMenu(""),BPmenu)
                       except:
                          self.session.openWithCallback(self.FantasticMenu(""),BP_Menu)
                    else:
                       self.session.openWithCallback(self.FantasticMenu,MessageBox,"Plugin %s is not available !" %mftextargument, MessageBox.TYPE_INFO)
                 else:
                    self.session.openWithCallback(self.FantasticMenu,MessageBox,"Plugin %s is not installed !" %mftextargument, MessageBox.TYPE_INFO)
                    
           elif mfcommand is "R":
              if mfintargument == 3:
                 self.session.openWithCallback(self.FantasticMenu,MessageBox,"Restarting Enigma2", MessageBox.TYPE_INFO, timeout=5)
                 TryQuitMainloop(self.session,mfintargument)
              elif mfintargument == 2:
                 self.session.openWithCallback(self.FantasticMenu,MessageBox,"Restarting IPbox", MessageBox.TYPE_INFO, timeout=5)
                 TryQuitMainloop(self.session,mfintargument)
              elif mfintargument == 1:
                 self.session.openWithCallback(self.FantasticMenu,MessageBox,"Entering Deepstandby", MessageBox.TYPE_INFO, timeout=5)
                 TryQuitMainloop(self.session,mfintargument)
              else:
                 pass
           elif mfcommand is "I":
              if os.path.exists("%s/%s.txt" %(fantastic_pluginpath,mfexecute)) is True:
                 menufile="%s/%s.txt" %(fantastic_pluginpath,mfexecute)
                 mf = open(menufile,"r")
                 mfexecute=mf.readline()
                 mf.close()
                 self.session.openWithCallback(self.FantasticMenu,MessageBox,mfexecute, MessageBox.TYPE_INFO, timeout=mfintargument)
              elif os.path.exists("/tmp/%s.txt" %(mfexecute)) is True:
                 menufile="/tmp/%s.txt" %(mfexecute)
                 mf = open(menufile,"r")
                 mfexecute=mf.readline()
                 mf.close()
                 self.session.openWithCallback(self.FantasticMenu,MessageBox,mfexecute, MessageBox.TYPE_INFO, timeout=mfintargument)
              else:
                 self.session.openWithCallback(self.FantasticMenu,MessageBox,mfexecute, MessageBox.TYPE_INFO, timeout=mfintargument)

           elif mfcommand is "D":
#              self.session.open(FantasticLCD,mftextargument)
              self.session.openWithCallback(self.FantasticMenu(""),FantasticLCD,mftextargument)

           elif mfcommand is "L":
              if mftextargument == "log":
                 os.system("echo %s > /tmp/fantasticlog.txt" %mfexecute) 
              elif mftextargument == "logappend":
                 os.system("echo %s >> /tmp/fantasticlog.txt" %mfexecute) 
              elif mftextargument == "reset":
                 if os.path.exists("/tmp/fantasticlog.txt") is True:
                    os.system("rm /tmp/fantasticlog.txt") 
              elif mftextargument == "wall":
                 os.system("wall %s" %mfexecute) 
              else:
                 print "[FANTASTIC] Logging: %s" %mfexecute
              self.FantasticMenu("")
           elif mfcommand is "M":
              self.FantasticMenu("")
           elif mfcommand is "T":
              self.session.openWithCallback(self.FantasticEnterText,InputBox, title=mfmenudescr, text=mftextargument, maxSize=False, type=Input.TEXT)
           elif mfcommand is "Y":
              self.session.openWithCallback(self.FantasticYN,MessageBox,mfmenudescr, MessageBox.TYPE_YESNO)
           else:
              pass

    def ListMenuFantastic(self):

        global mfcommand
        global mfmenu
        global mfmenuold
        global mfexecute
        global mfmenudescr
        global mfintargument
        global mftextargument

        menu = []

        menufile = "%s/%s.cfg" % (fantastic_pluginpath,mfmenu)
        mf = open(menufile,"r")

        for line in mf:
           parts=line.split(splitchar,3)
           index=len(parts)
           if index > 1:
              command=parts[0].upper().rstrip()
              if command[0] is not "S":
                 if index > 2:
                    menu.append(( str(parts[2]), line ))
                 else:
                    menu.append(( str(parts[1]), line ))
        mf.close()

        return menu

    def FantasticEnterText(self, mftext):

        global mfcommand
        global mfmenu
        global mfmenuold
        global mfexecute
        global mfmenudescr
        global mfintargument
        global mftextargument

        if mftext is None:
           mftextargument = None
           mfmenu="main"
           self.skipMF("No text passed, Exiting menu %s" % mfmenu)
        else:
           mftextargument = mftext
           self.FantasticMenu("")


    def FantasticYN(self,mfanswer):

        global mfcommand
        global mfmenu
        global mfmenuold
        global mfexecute
        global mfmenudescr
        global mfintargument
        global mftextargument

        if mfanswer is False:
           if mftextargument is not None:
              if mftextargument is not " ":
                 mfmenu=mftextargument
           
        self.FantasticMenu("")
           
    def skipMF(self,reason):
        self.session.open(MessageBox,_("Menu Fantastic exits, because %s") % reason, MessageBox.TYPE_WARNING)
        
#----------------------------------
    def addExtension(self, extension, key = None, type = EXTENSION_SINGLE):
		    self.list.append((type, extension, key))

    def updateExtension(self, extension, key = None):
      self.extensionsList.append(extension)
      if key is not None:
        if self.extensionKeys.has_key(key):
          key = None

      if key is None:
        for x in self.availableKeys:
          if not self.extensionKeys.has_key(x):
            key = x
            break

      if key is not None:
        self.extensionKeys[key] = len(self.extensionsList) - 1

    def updateExtensions(self):
      self.extensionsList = []
      self.availableKeys = [ "red", "green", "yellow", "blue", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
      self.extensionKeys = {}
      for x in self.list:
        if x[0] == self.EXTENSION_SINGLE:
          self.updateExtension(x[1], x[2])
        else:
          for y in x[1]():
            self.updateExtension(y[0], y[1])


    def showExtensionSelection(self):
      global pluginlist
      if pluginlist == "False":
        self.Plugins()
      pluginlist = "True"  
      self.updateExtensions()
      extensionsList = self.extensionsList[:]
      keys = []
      list = []
      for x in self.availableKeys:
        if self.extensionKeys.has_key(x):
          entry = self.extensionKeys[x]
          extension = self.extensionsList[entry]
          if extension[2]():
            name = str(extension[0]())
            list.append((extension[0](), extension))
            keys.append(x)
            extensionsList.remove(extension)
          else:
            extensionsList.remove(extension)
      for x in extensionsList:
        list.append((x[0](), x))
      keys += [""] * len(extensionsList)
      self.session.openWithCallback(self.extensionCallback, ChoiceBox, title=_("Please choose an extension..."), list = list, keys = keys)

    def extensionCallback(self, answer):
      if answer is not None:
        answer[1][1]()
        self.close()
        
    def Plugins(self):
      self.addExtension(extension = self.getPluginList, type = Fantastic.EXTENSION_LIST)

    def getPluginName(self, name):
      return name

    def getPluginList(self):
      list = []
      for p in plugins.getPlugins(where = PluginDescriptor.WHERE_EXTENSIONSMENU):
			  list.append(((boundFunction(self.getPluginName, p.name), boundFunction(self.runPlugin, p), lambda: True), None))
      return list

    def runPlugin(self, plugin):
      global servicelist
      plugin(session = self.session, servicelist = servicelist)
            
class FantasticServiceList(Screen):
    def __init__(self,session,service):
	Screen.__init__(self,session)
	self.session = session

        global servicelist
        
        if service is not None:
           servicelist=service
        else:
           servicelist=None
             
####################        

class FantasticButton(Screen):
    def __init__(self,session,button):
	Screen.__init__(self,session)
	self.session = session

        global mfcommand
        global mfmenu
        global mfmenuold
        global mfexecute
        global mfmenudescr
        global mfintargument
        global mftextargument

        if button is not None:
           mfmenuold=button
           mfmenu=button
           mfmenudescr="Menu Fantastic %s Button Menu" %button
        else:
           mfmenuold="main"
           mfmenu="main"
           mfmenudescr="Menu Fantastic Main Menu"


class FantasticBoot(Screen):
	def __init__(self,session):
		Screen.__init__(self,session)
		self.session = session
		
                mainmenufile = "%s/%s.cfg" % (fantastic_pluginpath,"main")
                if os.path.exists(mainmenufile) is True:
                   mfmain = open(mainmenufile,"r")
                   line=mfmain.readline()
                   parts=line.split(splitchar,3)
                   index=len(parts)
                   if index > 1:
                      command=parts[0].upper().rstrip()
                      # only if menu file contains S in first line startup is executed
                      if command[0] is "S":
                         if index > 3:
                            cmd=parts[3].rstrip()
                            if os.path.exists("%s/%s" %(fantastic_pluginpath,cmd)) is True:
                               os.system("%s/%s" % (fantastic_pluginpath,cmd))
                            else:
                               os.system("%s" % (cmd))
                            
                         mfmain.close()
   

class FantasticApplication(Screen):

        def __init__(self, session):
                self.session = session
        	self.skin = Fantastic.skin
		Screen.__init__(self, session)
		self.container=eConsoleAppContainer()
		self.container.appClosed.get().append(self.finished)
		self.runapp()
		
	def runapp(self):
	
                global mfcommand
                global mfmenu
                global mfmenuold
                global mfexecute
                global mfmenudescr
                global mfintargument
                global mftextargument

		eDBoxLCD.getInstance().lock()
		eRCInput.getInstance().lock()
		fbClass.getInstance().lock()
                self.session.nav.stopService()
                if os.path.exists(mfexecute) is True:
 		   self.container.execute("%s %s" %(mfexecute,mftextargument))
 		else:
 		   self.container.execute("%s/%s %s" %(fantastic_pluginpath,mfexecute,mftextargument))

	def finished(self,retval):
		fbClass.getInstance().unlock()
		eRCInput.getInstance().unlock()
		eDBoxLCD.getInstance().unlock()
		self.session.nav.playService(eServiceReference(config.tv.lastservice.value))



class FantasticLCD(Screen):
        # use size 0,0 to show text on LCD only
	skin = """
		<screen position="0,0" size="0,0" title="LCD Text" >
			<widget name="text" position="0,0" size="0,0" font="Regular;14" halign="center"/>
		</screen>"""
		
	def __init__(self, session, title = "LCD Text"):
		self.skin = FantasticLCD.skin
		Screen.__init__(self, session)

		self["text"] = Label("")

                # minimal actions to be able to exit after showing LCD Label
		self["actions"] = ActionMap(["WizardActions", "DirectionActions"], 
		{
			"ok": self.cancel,
			"back": self.cancel,
		}, -1)
                # now set passed Text Label for LCD output 		
		self.newtitle = title
		self.onShown.append(self.updateTitle)

	def updateTitle(self):
		self.setTitle(self.newtitle)
			
	def cancel(self):
		self.close()



