#######################################################################
#
#    Second InfoBar for Enigma-2
#    Vesion 2.7
#    Coded by Vali (c)2010
#    Support: www.dreambox-tools.info
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of the GNU General Public License
#    as published by the Free Software Foundation; either version 2
#    of the License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#######################################################################

from Screens.Screen import Screen
from Screens.PluginBrowser import PluginBrowser
from Screens.InfoBarGenerics import InfoBarPlugins, InfoBarSubserviceSelection, InfoBarExtensions
from Screens.InfoBar import InfoBar
from Screens.MessageBox import MessageBox
from Screens.EpgSelection import EPGSelection
from Plugins.Plugin import PluginDescriptor
from Components.ActionMap import ActionMap, HelpableActionMap
from Components.config import config, getConfigListEntry, ConfigSubsection, ConfigInteger, ConfigSelection, ConfigYesNo
from Components.ConfigList import ConfigListScreen
from Components.ServiceEventTracker import ServiceEventTracker
from Components.Sources.StaticText import StaticText 
from enigma import eTimer, iPlayableService

SIBbase__init__ = None
SIB_StartOnlyOneTime = False

IBSSbase__init__ = None
IBSS_StartOnlyOneTime = False

IBEbase__init__ = None
IBE_StartOnlyOneTime = False

config.plugins.SecondInfoBar  = ConfigSubsection()
config.plugins.SecondInfoBar.Mode = ConfigSelection(default="sib", choices=[
				("nothing", _("Not enabled")),
				("sib", _("Show Second-InfoBar")),
				("onlysib", _("Show ONLY Second-InfoBar")),
				("epglist", _("Show EPG-List"))
				])
config.plugins.SecondInfoBar.TimeOut = ConfigInteger(default=5, limits=(0, 30))
config.plugins.SecondInfoBar.HideNormalIB = ConfigYesNo(default=False)

def Plugins(**kwargs):
	return [PluginDescriptor(name="SecondInfoBar", description=_("Second-InfoBar setup"), where=PluginDescriptor.WHERE_MENU, fnc=SIBsetup),
			PluginDescriptor(where=PluginDescriptor.WHERE_SESSIONSTART, fnc=SIBautostart)]

def SIBsetup(menuid):
	if menuid != "osd_video_audio":
		return []
	return [(_("Second-InfoBar"), openSIBsetup, "sibsetup", None)]

def openSIBsetup(session, **kwargs):
	session.open(SIBsetupScreen)

class SIBsetupScreen(ConfigListScreen, Screen):
	skin = """
		<screen name="SIBsetupScreen" position="center,center" size="600,340" title="Second-InfoBar setup">
			<eLabel font="Regular;20" foregroundColor="#00ff4A3C" halign="center" position="20,308" size="120,26" text="Cancel"/>
			<eLabel font="Regular;20" foregroundColor="#0056C856" halign="center" position="165,308" size="120,26" text="Save"/>
			<eLabel font="Regular;16" halign="right" valign="center" position="300,308" size="260,26" text="coded: 2010 by Vali"/>
			<widget name="config" position="5,5" scrollbarMode="showOnDemand" size="590,300"/>
		</screen>"""
	def __init__(self, session):
		Screen.__init__(self, session)
		self.session = session
		self.MustRestart = (config.plugins.SecondInfoBar.Mode.value == "onlysib")
		self.setup_title = _("Second-InfoBar setup") 
		list = []
		list.append(getConfigListEntry(_("Second-InfoBar working mode"), config.plugins.SecondInfoBar.Mode))
		list.append(getConfigListEntry(_("Second-InfoBar timeout (in sec., 0 = wait for OK)"), config.plugins.SecondInfoBar.TimeOut))
		list.append(getConfigListEntry(_("Hide Infobar if Second-InfoBar shown"), config.plugins.SecondInfoBar.HideNormalIB))
		ConfigListScreen.__init__(self, list)
		self["actions"] = ActionMap(["OkCancelActions", "ColorActions"], 
									{
									"red": self.exit, 
									"green": self.save,
									"cancel": self.exit
									}, -1)
		self["key_red"] = StaticText(_("Cancel"))
		self["key_green"] = StaticText(_("OK"))
		self.onLayoutFinish.append(self.layoutFinished)

	def layoutFinished(self):
		self.setTitle(_(self.setup_title))

	def exit(self):
		for x in self["config"].list:
			x[1].cancel()
		self.close()

	def save(self):
		for x in self["config"].list:
			x[1].save()
		if (self.MustRestart ^ (config.plugins.SecondInfoBar.Mode.value == "onlysib")):
			self.session.open(MessageBox, _("GUI needs a restart to apply the new settings!!!"), MessageBox.TYPE_INFO, timeout=5)
		self.close()

def SIBautostart(reason, **kwargs):
	print "[2IB] Added SecondInfoBar"
	global SIBbase__init__
	global IBSSbase__init__
	global IBEbase__init__
	if "session" in kwargs:
		if SIBbase__init__ is None:
			SIBbase__init__ = InfoBarPlugins.__init__
		InfoBarPlugins.__init__ = InfoBarPlugins__init__
		InfoBarPlugins.switch = switch
		InfoBarPlugins.swOff = swOff
		if IBSSbase__init__ is None:
			IBSSbase__init__ = InfoBarSubserviceSelection.__init__
		InfoBarSubserviceSelection.__init__ = InfoBarSubserviceSelection__init__
		InfoBarSubserviceSelection.pluginsPanelOpen = pluginsPanelOpen
		try:
			from Plugins.Extensions.SoftcamManager.plugin import Emumanager
			print "[2IB] Emumanager imported from Plugins.Extensions.SoftcamManager.plugin"
		except:
			print "[2IB] Emumanager NOT imported from Plugins.Extensions.SoftcamManager.plugin"
			return
		if IBEbase__init__ is None:
			IBEbase__init__ = InfoBarExtensions.__init__
		InfoBarExtensions.__init__ = InfoBarExtensions__init__
		InfoBarExtensions.emuManagerOpen = emuManagerOpen
			

def InfoBarPlugins__init__(self):
	global SIB_StartOnlyOneTime
	if not SIB_StartOnlyOneTime:
		SIB_StartOnlyOneTime = True
		self["SIBActions"] = ActionMap(["SIBActions"], {"ok_but": self.switch, "exit_but": self.swOff}, -1)
		self.SIBtimer = eTimer()
		self.SIBtimer_conn = self.SIBtimer.timeout.connect(self.swOff)
		self.SIBdialog = self.session.instantiateDialog(SecondInfoBar, zPosition=1000)
		self.SIBdialog.shown = False

		def showSIB():
			doShowSIB(self)

		def checkSIBtimer():
			if config.plugins.SecondInfoBar.HideNormalIB.value:
				self.instance.setTransparent(0)
			if self.SIBtimer.isActive():
				self.SIBtimer.stop()

		if config.plugins.SecondInfoBar.Mode.value == "onlysib":
			self.onShow.append(showSIB)
		self.onHide.append(lambda: self.SIBdialog.hide())
		self.SIBdialog.onHide.append(checkSIBtimer)
	else:
		InfoBarPlugins.__init__ = InfoBarPlugins.__init__
		InfoBarPlugins.switch = None
		InfoBarPlugins.swOff = None
	SIBbase__init__(self)

def InfoBarSubserviceSelection__init__(self):
	global IBSS_StartOnlyOneTime
	if not IBSS_StartOnlyOneTime:
		IBSS_StartOnlyOneTime = True
		self["SubserviceSelectionAction"] = HelpableActionMap(self, "PluginsPanelOpen",
			{
				"pluginspanelOpen": (self.pluginsPanelOpen, _("Browse and manage your plugins...")),
				"subserviceSelection": (self.subserviceSelection, _("Subservice list..."))
			})

		self["SubserviceQuickzapAction"] = HelpableActionMap(self, "InfobarSubserviceQuickzapActions",
			{
				"nextSubservice": (self.nextSubservice, _("Switch to next subservice")),
				"prevSubservice": (self.prevSubservice, _("Switch to previous subservice"))
			}, -1)
		self["SubserviceQuickzapAction"].setEnabled(False)

		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evUpdatedEventInfo: self.checkSubservicesAvail
			})

		self.bsel = None
	else:
		InfoBarSubserviceSelection.__init__ = InfoBarSubserviceSelection.__init__
		InfoBarSubserviceSelection.pluginsPanelOpen = None
		IBSSbase__init__(self)

def InfoBarExtensions__init__(self):
	global IBE_StartOnlyOneTime
	if not IBE_StartOnlyOneTime:
		IBE_StartOnlyOneTime = True

		self.list = []

		self["InstantExtensionsActions"] = HelpableActionMap(self, "EmuManagerOpen",
			{
				"emumanagerOpen": (self.emuManagerOpen, _("Open Sat-Lodge emu manager...")),
				"extensions": (self.showExtensionSelection, _("view extensions...")),
			}, 1) # lower priority 
	else:
		InfoBarExtensions.__init__ = InfoBarExtensions.__init__
		InfoBarExtensions.powerPanelOpen = None
		IBEbase__init__(self)

def pluginsPanelOpen(self):
	self.session.open(PluginBrowser)

def emuManagerOpen(self):
	from Plugins.Extensions.SoftcamManager.plugin import Emumanager
	self.session.open(Emumanager)

def switch(self):
	if isinstance(self, InfoBar):
		if config.plugins.SecondInfoBar.Mode.value == "sib":
			if not self.shown:
				self.toggleShow()
			elif self.shown and not self.SIBdialog.shown:
				doShowSIB(self)
			elif self.SIBdialog.shown:
				self.hide()
			else:
				self.toggleShow()
		elif config.plugins.SecondInfoBar.Mode.value == "epglist":
			if self.shown:
				self.session.open(EPGSelection, self.session.nav.getCurrentlyPlayingServiceReference())
			else:
				self.toggleShow()
		else:
			self.toggleShow()

def doShowSIB(self):
	if config.plugins.SecondInfoBar.HideNormalIB.value:
		self.instance.setTransparent(255)
	self.hideTimer.stop()
	self.SIBdialog.show()
	SIBidx = config.plugins.SecondInfoBar.TimeOut.value
	if (SIBidx > 0):
		self.SIBtimer.start(SIBidx*1000, True)

def swOff(self):
	if isinstance(self, InfoBar):
		self.hide()

class SecondInfoBar(Screen):
	skin = """
		<screen flags="wfNoBorder" name="SecondInfoBar" position="center,350" size="720,200" title="Second Infobar">
			<eLabel text="Your skin do not support SecondInfoBar !!!" position="0,0" size="720,200" font="Regular;22" halign="center" valign="center"/>
		</screen>"""
	def __init__(self, session):
		Screen.__init__(self, session)
		self.session = session
		self.skin = SecondInfoBar.skin
