#
#  InfoBarExtensions Plugin-Order Setup
#
#  Coded by Dr.Best (c) 2011
#  Support: www.dreamboxtools.de
#
#  This plugin is licensed under the Creative Commons 
#  Attribution-NonCommercial-ShareAlike 3.0 Unported 
#  License. To view a copy of this license, visit
#  http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to Creative
#  Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
#
#  Alternatively, this plugin may be distributed and executed on hardware which
#  is licensed by Dream Multimedia GmbH.

#  This plugin is NOT free software. It is open source, you are allowed to
#  modify it (if you keep the license), but it may not be commercially 
#  distributed other than under the conditions noted above.
#

from Screens.Screen import Screen
from Screens.ChoiceBox import ChoiceBox
from Screens.MessageBox import MessageBox
from Components.Sources.StaticText import StaticText
from Components.ActionMap import ActionMap
from Components.ConfigList import ConfigListScreen
from Components.config import getConfigListEntry, NoSave, ConfigSelection
from Components.PluginComponent import plugins
from Plugins.Plugin import PluginDescriptor
from os import path as os_path
from pickle import load as pickle_load, dump as pickle_dump

CONFIG_FILE_PLUGINORDER = '/etc/enigma2/config_plugin_order'

def getPluginOrderDict():
	if os_path.exists(CONFIG_FILE_PLUGINORDER):
		pkl_file = open(CONFIG_FILE_PLUGINORDER, 'rb')
		if pkl_file:
			pluginorderdict = pickle_load(pkl_file)
			pkl_file.close()
			return pluginorderdict
	return {}

def savePluginOrderDict(dict):
	pkl_file = open(CONFIG_FILE_PLUGINORDER, 'wb')
	if pkl_file:
		pickle_dump(dict, pkl_file)
		pkl_file.close()

class InfoBarExtensionsChoiceBox(ChoiceBox):
	def __init__(self, session, title = "", list = [], keys = None, selection = 0, skin_name = [], titlebartext = None):
		ChoiceBox.__init__(self, session, title, list, keys, selection, skin_name, titlebartext)
		self["actions2"] = ActionMap(["InfobarMenuActions"], 
		{
			"mainMenu": self.mainMenuPressed
		}, -1)
	
	def mainMenuPressed(self):
		self.session.openWithCallback(self.infoBarExtensionsConfigScreenCallback, InfoBarExtensionsConfigScreen)

	def infoBarExtensionsConfigScreenCallback(self, value):
		self.close(value)

class InfoBarExtensionsConfigScreen(ConfigListScreen, Screen):
	skin = """
		<screen name="InfoBarExtensionsConfigScreen" position="center,center" size="550,400">
			<widget name="config" position="20,10" size="520,330" scrollbarMode="showOnDemand" />
			<ePixmap position="0,350" zPosition="4" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
			<ePixmap position="140,350" zPosition="4" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
			<ePixmap position="280,350" zPosition="4" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
			<ePixmap position="420,350" zPosition="4" size="140,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
			<widget source="key_red" render="Label" position="0,350" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
			<widget source="key_green" render="Label" position="140,350" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
		</screen>"""

	def __init__(self, session):	
		self.session = session
		Screen.__init__(self, session)
		self.title = _("Custom plugin-order config")
		self["actions"] = ActionMap(["SetupActions", "ColorActions"],
		{
			"green": self.keySave,
			"red": self.keyCancel,
			"cancel": self.keyCancel,
		}, -2)
		self["key_red"] = StaticText(_("Cancel"))
		self["key_green"] = StaticText(_("OK"))
		self.pluginOrder = getPluginOrderDict()
		self.list = [ ]
		self.choices = []
		for p in plugins.getPlugins(where = [PluginDescriptor.WHERE_EXTENSIONSMENU]):
			self.choices.append(str(p.name))
		self.choices.sort()
		self.choices.insert(0,"n/a")
		self.selection = {}
		i = 1
		while i <= 10:
			if i == 10:
				key = "0"
			else:
				key = str(i)
			self.selection[key] =  NoSave(ConfigSelection(default = self.getValue(key), choices = self.choices)) 
			self.list.append(getConfigListEntry(key, self.selection[key]))
			i += 1
		ConfigListScreen.__init__(self, self.list, session)

	def getValue(self, key):
		for item in self.pluginOrder.items():
			if item[1] == key:
				if item[0] in self.choices:
					return item[0]
		return "n/a"

	def keySave(self):
		pluginOrder = {}
		i = 0
		while i <= 9:
			key = str(i)
			name = self.selection[key].value
			if name == "n/a" or not pluginOrder.has_key(name):
				pluginOrder[name] = key
			else:
				self.session.open(MessageBox, _("%s is doubly present.\nPlease check your settings.") % name, MessageBox.TYPE_INFO)
				return
			i += 1
		savePluginOrderDict(pluginOrder)
		self.close(-1)

	def keyCancel(self):
		self.close(-2)
