#
# MerlinWebInterface
#
# Coded by dre (c) 2012 - 2021
# Support: board.dreamboxtools.de
# E-Mail: dre@dreamboxtools.de
#
# This plugin is open source but it is NOT free software.
#
# This plugin may only be distributed to and executed on hardware which
# is licensed by Dream Property GmbH.
# In other words:
# It's NOT allowed to distribute any parts of this plugin or its source code in ANY way
# to hardware which is NOT licensed by Dream Property GmbH.
# It's NOT allowed to execute this plugin and its source code or even parts of it in ANY way
# on hardware which is NOT licensed by Dream Property GmbH.
#
# If you want to use or modify the code or parts of it,
# you have to keep MY license and inform me about the modifications by mail.

from Components.Sources.Source import Source
from Components.config import config, configfile, ConfigYesNo, ConfigInteger, ConfigSelection, ConfigNumber, ConfigBoolean, ConfigOnOff, ConfigEnableDisable, ConfigSequence, ConfigSelectionNumber, ConfigSubDict, ConfigNothing, ConfigSlider
from Components.SystemInfo import SystemInfo
from Components.UsageConfig import *
from Tools.HardwareInfo import HardwareInfo
from enigma import eEnv
import xml.etree.cElementTree
import re
from collections import OrderedDict

class MerlinSettings(Source):
	MERLINSETTINGS = 0
	MERLINSETTINGSSAVE = 1
	CHANNELLISTSETTINGS = 2
	CHANNELLISTSETTINGSSAVE = 3
	DMMSETTINGS = 4
	DMMSETTINGSSAVE = 5
	#AVSETTINGS = 6
	#AVSETTINGSSAVE = 7
	
	def __init__(self, session, func):
		self.func = func
		self.session = session
		Source.__init__(self)

	def handleCommand(self, cmd):
		if self.func is self.MERLINSETTINGS:
			self.result = self.getMerlinSettings('merlin_setup.xml')
		elif self.func is self.MERLINSETTINGSSAVE:
			self.result = self.saveMerlinSettings(cmd)
		elif self.func is self.CHANNELLISTSETTINGS:
			self.result = self.getChannellistSettings() 
		elif self.func is self.CHANNELLISTSETTINGSSAVE:
			self.result = self.saveChannellistSettings(cmd)
		#elif self.func is self.DMMSETTINGS(cmd):
		elif self.func is self.DMMSETTINGS:
			self.result = self.getMerlinSettings('setup.xml')
		elif self.func is self.DMMSETTINGSSAVE:
			self.result = self.saveMerlinSettings(cmd)
		#elif self.func is self.AVSETTINGS:
			#self.result = self.getAVSettings()
		#elif self.func is self.AVSETTINGSSAVE:
			#self.result = self.saveAVSettings(cmd)
		else:
			self.result = False

	def getMerlinSettings(self, setupfile):
		merlinConfigList = []

		self.getDescription(merlinConfigList, setupfile)
		
		return merlinConfigList
	
	def getDescription(self, merlinConfigList, setupfile):
		try:
			setupfile_merlin = file('data/%s' %(setupfile), 'r')
		except:
			setupfile_merlin = file(eEnv.resolve('${datadir}/enigma2/%s' %(setupfile)), 'r')
		setupdom_merlin = xml.etree.cElementTree.parse(setupfile_merlin)
		setupfile_merlin.close()

		xmldata = setupdom_merlin.getroot()
		for x in xmldata.findall("setup"):
			key = x.get("key")
			category = x.get("title")
			print key
			if key in ("rc", "network", "RFmod", "satconfig", "osd", "lcd", "timezone", "avsetup", "keyboard", "harddisk"):
				continue
			else:
				self.addItems(merlinConfigList, x, category)
				
	def addItems(self, merlinConfigList, parentNode, category):
		currentCategory = None
		for x in parentNode:
			if x.tag == 'item':
				# Sections do not have a text
				if x.text is None:
					item_text = _(x.get("text", "??").encode("UTF-8"))
					print "item_text", item_text
					#merlinConfigList.append((item_text, None, None, None, ""))
					currentCategory = item_text
					continue
				item_config = x.text
				requires = x.get("requires")
				if requires and not SystemInfo.get(requires, False):
					continue

				item_text = _(x.get("text", "??").encode("UTF-8"))
				b = eval(x.text or "");
				if b == "":
					continue
				item = b
				item_type = "No Type"
				item_values = []
				item_setvalue = ""
				if isinstance(item, ConfigYesNo):
					item_type = "ConfigYesNo"
					item_values = item.getSelectionHTML(item_config, "MerlinSetting")
					item_setvalue = item.value
				elif isinstance(item, ConfigInteger):
					item_type = "ConfigInteger"
					item_setvalue = item.value
					item_values = item.getHTML(item_config, "MerlinSetting")
				elif isinstance(item, ConfigSelection):
					item_type = "ConfigSelection"
					item_setvalue =  item.getMulti(item.value)[1]
					item_values = item.getSelectionHTML(item_config, "MerlinSetting")
				elif isinstance(item, ConfigNumber):
					item_type = "ConfigNumber"
					item_setvalue = item.value
					item_values = item.getHTML(item_config, "MerlinSetting")
				elif isinstance(item, ConfigBoolean):
					item_type = "ConfigBoolean"
					item_setvalue =  item.getMulti(item.value)[1]
					item_values = item.getSelectionHTML(item_config, "MerlinSetting")
				elif isinstance(item, ConfigOnOff):
					item_type = "ConfigOnOff"
					item_setvalue =  item.getMulti(item.value)[1]
					item_values = item.getSelectionHTML(item_config, "MerlinSetting")
				elif isinstance(item, ConfigEnableDisable):
					item_type = "ConfigEnableDisable"
					item_setvalue =  item.getMulti(item.value)[1]
					item_values = item.getSelectionHTML(item_config, "MerlinSetting")
				elif isinstance(item, ConfigSequence):
					item_type = "ConfigSequence"
					item_setvalue =  item.getMulti(item.value)[1]
					item_values = item.getHTML(item_config, "MerlinSetting")
				elif isinstance(item, ConfigSet):
					item_type = "ConfigSet"
					item_setvalue = item.getMulti(item.value)[1]
					item_values = item.getSelectionHTML(item_config, "MerlinSetting")
					default_length = item.getDefaultLength()
				elif isinstance(item, ConfigSlider):
					item_type = "ConfigSlider"
					item_setvalue = item.getMulti(item.value)[1]
					item_values = item.getSelectionHTML(item_config, "AVSetting")
				item_cat = currentCategory
				print "item_cat is", item_cat
				merlinConfigList.append((item_text, item_config, item_setvalue, item_values, item_cat))

	def saveMerlinSettings(self, param):
		if config.plugins.MerlinWebInterface.allowsettingschange.value == True:
			print "[WebComponents.MerlinWebInterface] save settings with param = ", param
		
			configvaluelist = param['configvalues'].split(',')
			configentrylist = param['confignames'].split(',')
			configdict = dict(zip(configentrylist, configvaluelist))
		
			for k, v in configdict.iteritems():
				configobject = eval(k)
				if eval(k).value != str(v):
					if isinstance(configobject, ConfigNumber):
						configobject.value = int(v)
					elif isinstance(configobject, ConfigInteger):
						configobject.value = int(v)
					elif isinstance(configobject, (ConfigYesNo, ConfigBoolean, ConfigOnOff, ConfigEnableDisable)):
						if v == "True":
							tostore = True
						elif v == "False":
							tostore = False
						configobject.value = tostore
					elif isinstance(configobject, (ConfigSequence, ConfigSelection)):
						eval(k).value = v
					elif isinstance(configobject, ConfigSet):
						values = []
						values = v.split('#')
						values = map(int, values)
						#compare old and new again as first check will always return true for ConfigSet
						if eval(k).value != values:
							eval(k).value = values
					elif isinstance(configobject, ConfigSlider):
						configobject.value = int(v)
					eval(k).save()
			configfile.save()
		
			return (True, "Settings have been updated")
		else:
			return (False, "Settings have not been updated. Modification of settings is disabled.")
			
	def getChannellistSettings(self):
		
		merlinConfigList = []
		#forget about dynamically reading the config entries as it's not possible to get a description
		#self.searchConfigEntries(merlinConfigList, "/usr/lib/enigma2/python/Screens/ChannelSelectionDisplaySettings.py", "ChannellistSetting")

		configitems = OrderedDict([
		("config.usage.configselection_columnstyle" , _("Column style")),
		("config.usage.configselection_showrecordings" , _("Show recordings")),
		("config.usage.configselection_showdvbicons", _("Show DVB-icons")),
		("config.usage.configselection_showlistnumbers" , _("Show service numbers")),
		("config.usage.configselection_listnumbersalignment", _("Service number alignment")),
		("config.usage.configselection_showpicons" , _("Show Picons")),
		("config.usage.configselection_piconspath" , _("Picons path")),
		("config.usage.configselection_secondlineinfo" , _("2nd line info")),
		("config.usage.configselection_showservicename" , _("Show service name")),
		("config.usage.show_event_progress_in_servicelist" , _("Show event-progress")),
		("config.usage.configselection_progressbarposition" , _("Event-progessbar position")),
		("config.usage.configselection_servicenamecolwidth" , _("Service name column width")),
		("config.usage.configselection_showadditionaltimedisplay" , _("Additional event-time info")),
		("config.usage.configselection_additionaltimedisplayposition" , _("Additional event-time position")),
		("config.usage.configselection_tagBouquetServices" , _("Tag bouquet services")),

		#("config.merlin2.configselection_showsettingsincontextmenu" , _("Show settings in channel context menu"))
		
		])
		
		showPicons = False
		useColumnStyle = False
		useBigPicons = False
		showEventProgress = False
		showServiceName = False
		additionalEventInfo = 0
		tagBouquetServices = False
	
		c = eval("config.usage.configselection_bigpicons" or "")
		if c != "":
			item = c
			useBigPicons = item.value
	
		for entry in configitems.keys():
			item_config = entry
			b = eval(item_config or "")
			if b == "":
				continue
			item = b
			print item_config
			item_text = configitems.get(entry)
			item_type = "No Type"
			item_values = []
			item_setvalue = ""
			skipList = []
			if isinstance(item, ConfigYesNo):
				item_type = "ConfigYesNo"
				item_values = item.getSelectionHTML(item_config, "ChannellistSetting")
				item_setvalue = item.value
			elif isinstance(item, ConfigInteger):
				item_type = "ConfigInteger"
				item_setvalue = item.value
				item_values = item.getHTML(item_config, "ChannellistSetting")
			elif isinstance(item, ConfigSelection):
				item_type = "ConfigSelection"
				item_setvalue =  item.getMulti(item.value)[1]
				#Remove  progress bar position option 1 when column style or show service name is not used
				if item_config == "config.usage.configselection_progressbarposition" and (useColumnStyle == False or showServiceName == False):
					skipList.append("1")
				item_values = item.getSelectionHTML(item_config, "ChannellistSetting", skipList)
			elif isinstance(item, ConfigNumber):
				item_type = "ConfigNumber"
				item_setvalue = item.value
				item_values = item.getHTML(item_config, "ChannellistSetting")
			elif isinstance(item, ConfigBoolean):
				item_type = "ConfigBoolean"
				item_setvalue =  item.getMulti(item.value)[1]
				item_values = item.getSelectionHTML(item_config, "ChannellistSetting", skipList)
			elif isinstance(item, ConfigOnOff):
				item_type = "ConfigOnOff"
				item_setvalue =  item.getMulti(item.value)[1]
				item_values = item.getSelectionHTML(item_config, "ChannellistSetting")
			elif isinstance(item, ConfigEnableDisable):
				item_type = "ConfigEnableDisable"
				item_setvalue =  item.getMulti(item.value)[1]
				item_values = item.getSelectionHTML(item_config, "ChannellistSetting")
			elif isinstance(item, ConfigSequence):
				item_type = "ConfigSequence"
				item_setvalue =  item.getMulti(item.value)[1]
				item_values = item.getHTML(item_config, "ChannellistSetting")
			
			#set showPicons
			if item_config == "config.usage.configselection_showpicons" and item.value == True:
				showPicons = True
			
			#set useColumnStyle	
			if item_config == "config.usage.configselection_columnstyle" and item.value == True:
				useColumnStyle = True
				
			#set showEventProgress
			if item_config == "config.usage.show_event_progress_in_servicelist" and item.value == True:
				showEventProgress = True
				
			#set additionalEventInfo
			if item_config == "config.usage.configselection_additionaltimedisplayposition":
				additionalEventInfo = item.value
				
			#set tagBouquetServices
			if item_config == "config.usage.configselection_tagBouquetServices" and item.value == True:
				tagBouquetServices = True
				
			#set showServiceName
			if item_config == "config.usage.configselection_showservicename" and item.value == True:
				showServiceName = True

			#Don't show "Picons path" option when show Picons is not activated
			if item_config == "config.usage.configselection_piconspath" and showPicons == False:
				print "[MerlinSettings.py]: hiding piconspath"
				continue
			
			#Don't show "2nd line info" option when column style and big picons are not used or column style is used and big picons are not used
			if item_config == "config.usage.configselection_secondlineinfo" and (useColumnStyle == False or useColumnStyle == True and useBigPicons == False):
				print "[MerlinSettings.py]: hiding secondlineinfo"
				continue
				
			#Don't show "Show service name" option when column style is not used			
			if item_config == "config.usage.configselection_showservicename" and useColumnStyle == False:
				print "[MerlinSettings.py]: hiding showservicename"			
				continue
				
			#Don't show "Event-progressbar position" option when show event progress is not activated
			if item_config == "config.usage.configselection_progressbarposition" and showEventProgress == False:
				print "[MerlinSettings.py]: hiding progressbarposition"				
				continue
				
			#Don't show "Service name column width" when column style is not used
			if item_config == "config.usage.configselection_servicenamecolwidth" and useColumnStyle == False:
				print "[MerlinSettings.py]: hiding servicenamecolwidth"
				continue
				
			#Don't show "Additional event-time position" option when is not activated
			if item_config == "config.usage.configselection_additionaltimedisplayposition" and additionalEventInfo == "0":
				print "[MerlinSettings.py]: hiding additionaltimedisplayposition"				
				continue
				
			#Don't show "Tagged Bouquet Services" option when is not activated
			if item_config == "config.usage.configselection_tagBouquetServices" and tagBouquetServices == False:
				print "[MerlinSettings.py]: hiding tagBouquetServices"
				continue
			item_cat = ""
			merlinConfigList.append((item_text, item_config, item_setvalue, item_values, item_cat))			
		
		
		return merlinConfigList
	
	def saveChannellistSettings(self, param):
		if config.plugins.MerlinWebInterface.allowsettingschange.value == True:
			print "[WebComponents.MerlinWebInterface] save settings with param = ", param
			
			configvaluelist = param['configvalues'].split(',')
			configentrylist = param['confignames'].split(',')
			configdict = dict(zip(configentrylist, configvaluelist))
			
			#TODO: implement handling for big picons and picons path
			
			for k, v in configdict.iteritems():
				configobject = eval(k)
				if eval(k).value != str(v):
					if isinstance(configobject, ConfigNumber):
						configobject.value = int(v)
					elif isinstance(configobject, ConfigInteger):
						configobject.value = int(v)
					elif isinstance(configobject, (ConfigYesNo, ConfigBoolean, ConfigOnOff, ConfigEnableDisable)):
						if v == "True":
							tostore = True
						elif v == "False":
							tostore = False
						configobject.value = tostore
					elif isinstance(configobject, (ConfigSequence, ConfigSelection)):
						eval(k).value = v
					eval(k).save()
			configfile.save()
			
			c = eval("config.usage.configselection_showpicons" or "")
			if c != "":
				item = c
				configobject = eval("config.usage.configselection_bigpicons")
				configobject2 = eval("config.usage.configselection_piconspath")
				if item.value == False:
					if isinstance(configobject, (ConfigYesNo, ConfigBoolean, ConfigOnOff, ConfigEnableDisable)):
						configobject.value = "False"
						configobject.save()
					if isinstance(configobject2, (ConfigSequence, ConfigSelection)):
						configobject2.value = None
						configobject2.save()
				elif item.value == True:
					if isinstance(configobject2, (ConfigSequence, ConfigSelection)):
						pathvalue = configobject2.value
						if pathvalue is not None:
							if pathvalue.endswith('picon/'):
								if isinstance(configobject, (ConfigYesNo, ConfigBoolean, ConfigOnOff, ConfigEnableDisable)):
									configobject.value = True
									configobject.save()
								else:
									if isinstance(configobject, (ConfigYesNo, ConfigBoolean, ConfigOnOff, ConfigEnableDisable)):
										configobject.value = False
										configobject.save()
			configfile.save()
						 
					
			
			return (True, "Settings have been updated. Please check if new settings are available due to the latest changes")
		else:
			return (False, "Settings have not been updated. Modification of settings is disabled.")

	"""
	def getAVSettings(self):
		
		merlinConfigList = []
		
		configitems = OrderedDict([
		(_("Video"), None),
		("config.av.videoport", _("Video Output")),
		("config.av.preferred_modes_only", _("Preferred modes only")),
		("config.av.videomode", _("Mode")),
		("config.av.videorate", _("Refresh Rate")),
		("config.av.aspect" , _("Aspect Ratio")),
		("config.av.policy_43" , _("Display 4:3 content as")),
		("config.av.policy_169" , _("Display >16:9 content as")),
		("config.av.colorformat" , _("Color Format")),
		("config.av.wss" , _("WSS on 4:3")),
		("config.av.vcrswitch" , _("Auto scart switching")),
		("config.av.osd_alpha", _("OSD visibility")),
		("config.av.scaler_sharpness", _("Scaler sharpness")),
		("config.av.sync_mode", _("Sync mode")),
		("config.av.hlg_support", _("HLG Support")),
		("config.av.hdr10_support", _("HDR10 Support")),
		("config.av.allow_12bit", _("Allow 12bit")),
		("config.av.allow_10bit", _("Allow 10bit")),
		(_("Audio"), None),
		("config.av.defaultac3" , _("AC3 default")),
		("config.av.downmix_ac3" , _("AC3 downmix")),
		("config.av.generalAC3delay" , _("General AC3 Delay")),
		("config.av.generalPCMdelay" , _("General PCM Delay")),
		("config.av.convert_ac3plus", _("Convert AC3+ to AC3"))
		])
		
		# todo:ConfigSlider: getSteps as select
		
		currentPort = None
		currentMode = None
		modedict = {}
		ratedict = {}
		
		is_auto = config.av.aspect.value == "auto"
		
		level = config.usage.setup_level.index
		
		currentCategory = ""
		hasScaler = False
		hasOSDAlpha = False
		hasHDRSupport = False
		isOE26 = True
		try:
			from Components.DisplayHardware import DisplayHardware
			dw_instance = DisplayHardware.instance
		except:
			isOE26 = False
			
			
		if isOE26:
			hasScaler = SystemInfo["CanChangeScalerSharpness"]
			hasOSDAlpha = SystemInfo["CanChangeOsdAlpha"]
			hasHDRSupport = SystemInfo["HDRSupport"]
			canDownmixAC3 = SystemInfo["CanDownmixAC3"]
			hasAC3PlusSupport = SystemInfo["HasAC3PlusSupport"]
			supportsAC3PlusTranscode = SystemInfo["SupportsAC3PlusTranscode"] 

		for entry, item_text in configitems.iteritems():
			item_config = entry
			if item_text is None:
				currentCategory = entry
				continue
			if not hasScaler and item_config == "config.av.scaler_sharpness":
				continue
			if not supportsAC3PlusTranscode and item_config == "config.av.convert_ac3plus":
				continue
			if not isOE26 and item_config == "config.av.sync_mode":
				continue
			try:
				b = eval(item_config or "")
			except:
				b = ""
			if b == "":
				continue
			item = b

			item_type = "No Type"
			item_values = []
			item_setvalue = ""
			skipList = []
			setDisabled = ""
			jsfunc = ""
			
			if isinstance(item, ConfigYesNo):
				item_type = "ConfigYesNo"
				item_setvalue = item.value
				
				if item_config == "config.av.defaultac3" and level <1:
					setDisabled = "disabled"
		
				if item_config == "config.av.downmix_ac3":
					if SystemInfo["CanDownmixAC3"] and level >= 1:
						pass
					else:
						setDisabled = "disabled"
						
				item_values = item.getSelectionHTML(item_config, "AVSetting", skipList, setDisabled)
			elif isinstance(item, ConfigNothing):
				continue
			elif isinstance(item, ConfigInteger):
				item_type = "ConfigInteger"
				item_setvalue = item.value
				item_values = item.getHTML(item_config, "AVSetting")
			elif isinstance(item, ConfigSelection):
				item_type = "ConfigSelection"
				item_setvalue =  item.getMulti(item.value)[1]
				#save current video ouptput as it is needed for videomode
				if item_config == "config.av.videoport":
					currentPort = item.getMulti(item.value)[1]
					ports = item.getChoices()
					jsfunc = 'onchange="enableDisableSelect(this)"'
				elif item_config == "config.av.aspect":
					if force_widescreen:
						#do not show aspect config when widescreen is used
						setDisabled = "disabled"
					jsfunc = 'onchange="enableDisableSelect(this)"'
				elif item_config == "config.av.colorformat" and currentPort != "Scart":
					#do not show colorformat when mode is not Scart
					setDisabled = "disabled"
				elif item_config == "config.av.policy_43" or item_config == "config.av.policy_169":
					if is_widescreen:
						pass
					elif config.av.aspect.value == "4_3" and item_config == "config.av.policy_169":
						pass
					else:
						setDisabled = "disabled"
				elif item_config == "config.av.convert_ac3plus":
					if SystemInfo["SupportsAC3PlusTranscode"] and level >= 1:
						pass
					else:
						setDisabled = "disabled"
				#type is ConfigSelectionNumber but it is considered as ConfigSelection...
				elif (item_config == "config.av.generalAC3delay" or item_config == "config.av.generalPCMdelay") and level < 1:
					item_type = "ConfigSelectionNumber"
					setDisabled = "disabled"
				elif item_config in ("config.av.hlg_support", "config.av.hdr10_support","config.av.allow_12bit", "config.av.allow_10bit" ):
					if SystemInfo["HDRSupport"] and level >= 1:
						pass
					else:
						setDisabled = "disabled"
						

				item_values = item.getSelectionHTML(item_config, "AVSetting", skipList, setDisabled, jsfunc)
			elif isinstance(item, ConfigNumber):
				item_type = "ConfigNumber"
				item_setvalue = item.value
				item_values = item.getHTML(item_config, "AVSetting")
			elif isinstance(item, ConfigBoolean):
				item_type = "ConfigBoolean"
				item_setvalue =  item.getMulti(item.value)[1]
				if item_config == "config.av.vcrswitch":
					#vcrswitch is ConfigEnableDisable. But it's considered as ConfigBoolean...
					item_type = "ConfigEnableDisable"
					if currentPort == "Scart" and SystemInfo["ScartSwitch"] and level >= 1:
						pass
					else:
						#do not show scart switch config when no scart is available or selected output is not scart
						setDisabled = "disabled"
				if item_config == "config.av.wss":
					#wss is ConfigEnableDisable. But it's considered as ConfigBoolean...
					item_type = "ConfigEnableDisable"
					if currentPort == "Scart" and level >= 1:
						pass
					else:
						#do not show wss when output is not scart
						setDisabled = "disabled"
				item_values = item.getSelectionHTML(item_config, "AVSetting", skipList, setDisabled, jsfunc)				
			elif isinstance(item, ConfigOnOff):
				item_type = "ConfigOnOff"
				item_setvalue =  item.getMulti(item.value)[1]
				item_values = item.getSelectionHTML(item_config, "AVSetting")
			elif isinstance(item, ConfigEnableDisable):
				item_type = "ConfigEnableDisable"
				item_setvalue =  item.getMulti(item.value)[1]
				item_values = item.getSelectionHTML(item_config, "AVSetting")
			elif isinstance(item, ConfigSequence):
				item_type = "ConfigSequence"
				item_setvalue =  item.getMulti(item.value)[1]
				item_values = item.getHTML(item_config, "AVSetting")
			elif isinstance(item, ConfigSubDict):
				item_type = "ConfigSubDict"
				if item_config == "config.av.videomode":
					#box = HardwareInfo().get_device_name()
					#if box in ('dm500hd', 'dm500hdv2', 'dm800se', 'dm800sev2', 'dm7020hd'):
					if currentPort == 'HDMI':
						if not "HDMI" in item.keys():
							keyname = 'DVI'
						else:
							keyname = "HDMI"
					elif currentPort == 'HDMI-PC':
						if not "HDMI-PC" in item.keys():
							keyname = 'DVI-PC'
						else: keyname = "HDMI-PC"
						
					itemkey = item[keyname]
					
					if isinstance(itemkey, ConfigSelection):
						item_type = "ConfigSelection"
						item_setvalue = item[keyname].value
						#save current mode as it is needed for videorate
						currentMode = item_setvalue
						video_hw = None
						display_hw = None
						try:
							from Plugins.SystemPlugins.Videomode.VideoHardware import video_hw
						except:
							try:
								from Components.DisplayHardware import DisplayHardware
								display_hw = DisplayHardware.instance
							except:
								pass
						force_widescreen = False
						if video_hw is not None:
							force_widescreen = video_hw.isWidescreenMode(currentPort, currentMode)
						elif display_hw is not None:
							force_widescreen = display_hw.isWidescreen(currentMode)
						is_widescreen = force_widescreen or config.av.aspect.value in ("16_9", "16_10")
						
						temp = ""
						for port in ports:
							modedict[port[0]] = item[port[0]].getChoices()

							if port[0] == keyname:
								hidden = "0"
							else:
								hidden = "1"
								
							temp += item[port[0]].getSelectionHTML(item_config, "AVSetting", skipList, "", 'onchange="enableDisableSelect(this)"', hidden, port[0])
						#item_config ist hier wohl noch falsch
						item_values = temp

				if item_config == "config.av.videorate":
					itemkey = item[currentMode]
					
					if isinstance(itemkey, ConfigSelection):
						item_type = "ConfigSelection"
						item_setvalue = item[currentMode].value
						
						if currentMode == "PC":
							item_text = _("Resolution")
							
						temp = ""
						for k, v in modedict.iteritems():
							for mode in v:
								if isinstance(mode, tuple):
									mode = mode[0]
								ratedict[mode] = item[mode].getChoices()
							
								if mode == currentMode and k == keyname:
									hidden = "0"
								else:
									hidden = "1"
								
								portmode = "%s,%s" %(k, mode)
									
								temp += item[mode].getSelectionHTML(item_config, "AVSetting", skipList, "", "", hidden, portmode)
						#item_config ist hier wohl noch falsch						
						item_values = temp
			elif isinstance(item, ConfigSlider):
				item_type = "ConfigSlider"
				if item_config == "config.av.scaler_sharpness":
					if hasScaler:
						item_setvalue = item.getMulti(item.value)[1]
						item_values = item.getSelectionHTML(item_config, "AVSetting")
					else:
						setDisabled = "disabled"
				elif item_config == "config.av.osd_alpha":
					if SystemInfo["CanChangeOsdAlpha"]:
						item_setvalue = item.getMulti(item.value)[1]
						item_values = item.getSelectionHTML(item_config, "AVSetting")
					else:
						setDisabled = "disabled"
			else:
				print "ConfigElement is not handled", item_config
				continue
			
			item_cat = currentCategory
			print "itemCat", item_cat
			
			merlinConfigList.append((item_text, item_config, item_setvalue, item_values, item_cat))			
		
		
		return merlinConfigList
	
	def saveAVSettings(self, param):
		if config.plugins.MerlinWebInterface.allowsettingschange.value == True:
			print "[WebComponents.MerlinWebInterface] save settings with param = ", param
			
			configvaluelist = param['configvalues'].split(',')
			configentrylist = param['confignames'].split(',')
			configdict = dict(zip(configentrylist, configvaluelist))
			
			for k, v in configdict.iteritems():
				configobject = eval(k)
				
				if eval(k).value != str(v):
					if isinstance(configobject, ConfigNumber):
						configobject.value = int(v)
					elif isinstance(configobject, ConfigInteger):
						configobject.value = int(v)
					elif isinstance(configobject, (ConfigYesNo, ConfigBoolean, ConfigOnOff, ConfigEnableDisable)):
						if v == "True":
							tostore = True
						elif v == "False":
							tostore = False
						configobject.value = tostore
					elif isinstance(configobject, (ConfigSequence, ConfigSelection, ConfigSelectionNumber)):
						eval(k).value = v
					elif isinstance(configobject, ConfigSlider):
						configobject.value = int(v)
					else:
						print "not known", k
					eval(k).save()
			configfile.save()
			
			return (True, "Settings have been updated. Please restart enigma2 to activate them.")
		else:
			return (False, "Settings have not been updated. Modification of settings is disabled.")
	"""

	def getText(self):
		self.handleCommand(None)
		if self.result:
			return str(self.result)
		else:
			return ""

	def getList(self):
		self.handleCommand(None)
		list = self.result
		if list is None:
			list = ()

		return list
		
	text = property(getText)
	list = property(getList)
	lut = {"Name": 0, "Config": 1, "DefaultValue": 2, "Value": 3, "Category": 4}
