#######################################################################
#
#    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.
#
#######################################################################

#######################################################################
#
#    Modified by gigilangh for the Power-Sat Team
#
#######################################################################

from Screens.Screen import Screen
from Screens.ChannelSelection import ChannelSelection, MODE_TV, MODE_RADIO
from Screens.EpgSelection import EPGSelection
from Screens.InfoBar import InfoBar
from Screens.InfoBarGenerics import InfoBarPlugins, InfoBarSubserviceSelection, InfoBarExtensions, InfoBarNumberZap, InfoBarPiP, NumberZap
from Screens.MessageBox import MessageBox
from Screens.PluginBrowser import PluginBrowser
from Components.ActionMap import ActionMap, HelpableActionMap
from Components.config import config, getConfigListEntry, ConfigSubsection, ConfigInteger, ConfigSelection, ConfigYesNo
from Components.ConfigList import ConfigListScreen
from Components.Harddisk import harddiskmanager
from Components.ServiceEventTracker import ServiceEventTracker
from Components.Sources.StaticText import StaticText
from Plugins.Plugin import PluginDescriptor
from enigma import eTimer, iPlayableService, eEnv

#######################################################################################################################################################

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)

PICONSPATH_DEFAULT = eEnv.resolve("${datadir}/enigma2")

def getMountpoints():
	mountpoints = [(PICONSPATH_DEFAULT, PICONSPATH_DEFAULT)]
	for p in harddiskmanager.getConfiguredStorageDevices():
		mountpoints.append((p.mountpoint, p.mountpoint))
		print "[2IB] Picons path:", p.mountpoint
	return mountpoints

config.plugins.InfoBar = ConfigSubsection()
config.plugins.InfoBar.PiconsPath = ConfigSelection(default = PICONSPATH_DEFAULT, choices = getMountpoints())
config.plugins.InfoBar.NoPanic = ConfigYesNo(default=False)

#######################################################################################################################################################

def Plugins(**kwargs):
	return [PluginDescriptor(name="InfoBar & Second-InfoBar", description=_("InfoBar & 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 [(_("InfoBar & 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 = _("InfoBar & Second-InfoBar setup")
		list = []
		list.append(getConfigListEntry(_("Second-InfoBar")))
		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(_("InfoBar")))
		list.append(getConfigListEntry(_("Hide InfoBar if Second-InfoBar shown"), config.plugins.SecondInfoBar.HideNormalIB))
		list.append(getConfigListEntry(_("Miscellaneous")))
		config.plugins.InfoBar.PiconsPath.setChoices(getMountpoints(), default = PICONSPATH_DEFAULT)
		list.append(getConfigListEntry(_("Picons path"), config.plugins.InfoBar.PiconsPath))
		list.append(getConfigListEntry(_("No panic function (press 0 to zap on channel 1 and clear channel history)"), config.plugins.InfoBar.NoPanic))
		ConfigListScreen.__init__(self, list)
		self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
									{
									"red": self.keyCancel,
									"green": self.keySave,
									"cancel": self.keyCancel
									}, -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 saveAll(self):
		for x in self["config"].list:
			if len(x) > 1:
				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)

#######################################################################################################################################################

def SIBautostart(reason, **kwargs):
	print "[2IB] Added Second-InfoBar"
	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
		InfoBarNumberZap.keyNumberGlobal = InfoBarNumberZapkeyNumberGlobal
		InfoBarPiP.swapPiP = InfoBarPiPswapPiP
		try:
			from Plugins.SatLodge.SatLodgeEmu.plugin import Emumanager
			print "[2IB] Emu manager imported from Plugins.SatLodge.SatLodgeEmu.plugin"
		except:
			print "[2IB] Emu manager NOT imported from Plugins.SatLodge.SatLodgeEmu.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.SatLodge.SatLodgeEmu.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 swOff(self):
	if isinstance(self, InfoBar):
		self.hide()

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 InfoBarNumberZapkeyNumberGlobal(self, number):
	print "[2IB] You pressed number", str(number)
	if number == 0:
		if isinstance(self, InfoBarPiP) and self.pipHandles0Action():
			self.pipDoHandle0Action()
		else:
			print "[2IB] (MODE_TV = 0 - MODE_RADIO = 1) Mode:", str(self.servicelist.mode)
			if config.plugins.InfoBar.NoPanic.value and self.servicelist.mode == MODE_TV:
				self.servicelist.history = self.servicelist.history_tv = []
				self.servicelist.history_pos = 0
				self.zapToNumber(2) # rebuild a minimal history
				self.zapToNumber(1) # don't worry :-)
				print "[2IB] TV history cleared :-)"
			else:
				self.servicelist.recallPrevService()
	else:
		if self.has_key("TimeshiftActions") and not self.timeshift_enabled:
			self.session.openWithCallback(self.numberEntered, NumberZap, number)

def InfoBarPiPswapPiP(self):
	swapservice = self.session.nav.getCurrentlyPlayingServiceReference()
	if self.session.pip.servicePath:
		print "[2IB] Swap PIP"
		servicepath = self.servicelist.getCurrentServicePath()
		if servicepath:
			ref = servicepath[len(servicepath)-1]
			pipref = self.session.pip.getCurrentService()
			self.session.pip.playService(swapservice)
			self.servicelist.setCurrentServicePath(self.session.pip.servicePath)
			if pipref.toString() != ref.toString(): # is a subservice ?
				self.session.nav.stopService() # stop portal
				self.session.nav.playService(pipref) # start subservice
			self.session.pip.servicePath = servicepath

#######################################################################################################################################################

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