from __future__ import division
from __future__ import print_function
from enigma import eRCInput, getPrevAsciiCode
from Tools.NumericalTextInput import NumericalTextInput, NumericalHexInput
from Tools.Directories import resolveFilename, SCOPE_CONFIG, fileExists
from Tools.IO import saveFile
from copy import copy as copy_copy
from os import path as os_path
from time import localtime, strftime
from netaddr import IPAddress
from ast import literal_eval

from Tools.Log import Log
import six
from six import unichr
from six.moves import range
# ConfigElement, the base class of all ConfigElements.

# it stores:
#   value    the current value, usefully encoded.
#            usually a property which retrieves _value,
#            and maybe does some reformatting
#   _value   the value as it's going to be saved in the configfile,
#            though still in non-string form.
#            this is the object which is actually worked on.
#   default  the initial value. If _value is equal to default,
#            it will not be stored in the config file
#   saved_value is a text representation of _value, stored in the config file
#
# and has (at least) the following methods:
#   save()   stores _value into saved_value,
#            (or stores 'None' if it should not be stored)
#   load()   loads _value from saved_value, or loads
#            the default if saved_value is 'None' (default)
#            or invalid.
#
class ConfigElement(object):
	def __init__(self):
		self.saved_value = None
		self.save_forced = True
		self.save_disabled = False
		self.__notifiers = { }
		self.__notifiers_final = { }
		self.enabled = True
		self.key = 0

	def getNotifiers(self):
		return [func for (key, func, val, call_on_save_and_cancel) in six.itervalues(self.__notifiers)]

	def setNotifiers(self, val):
		print("just readonly access to notifiers is allowed! append/remove doesnt work anymore! please use addNotifier, removeNotifier, clearNotifiers")

	notifiers = property(getNotifiers, setNotifiers)

	def getNotifiersFinal(self):
		return [func for (key, func, val, call_on_save_and_cancel) in six.itervalues(self.__notifiers_final)]

	def setNotifiersFinal(self, val):
		print("just readonly access to notifiers_final is allowed! append/remove doesnt work anymore! please use addNotifier, removeNotifier, clearNotifiers")

	notifiers_final = property(getNotifiersFinal, setNotifiersFinal)

	# you need to override this to do input validation
	def setValue(self, value):
		self._value = value
		self.changed()

	def getValue(self):
		return self._value

	value = property(getValue, setValue)

	# you need to override this if self.value is not a string
	def fromstring(self, value):
		return value

	# you can overide this for fancy default handling
	def load(self):
		sv = self.saved_value
		if not sv:
			self.value = self.default
		else:
			self.value = self.fromstring(sv)

	def tostring(self, value):
		return str(value)

	# you need to override this if str(self.value) doesn't work
	def save(self):
		if self.save_disabled or (self.value == self.default and not self.save_forced):
			self.saved_value = None
		else:
			self.saved_value = self.tostring(self.value)
		self.changed(save_or_cancel=True)
		self.changedFinal(save_or_cancel=True)

	def cancel(self):
		self.load()
		self.changed(save_or_cancel=True)
		self.changedFinal(save_or_cancel=True)

	def isChanged(self):
		sv = self.saved_value
		if sv is None and self.value == self.default:
			return False
		return self.tostring(self.value) != sv

	def changed(self, save_or_cancel=False):
		for (func, val) in sorted(six.iteritems(self.__notifiers)):
			strval = str(self.value)
			if (val[3] and save_or_cancel) or (save_or_cancel == False and val[2] != strval):
				self.__notifiers[func] = (val[0], val[1], strval, val[3])
				val[1](self)

	def changedFinal(self, save_or_cancel=False):
		for (func, val) in sorted(six.iteritems(self.__notifiers_final)):
			strval = str(self.value)
			if (val[3] and save_or_cancel) or (save_or_cancel == False and val[2] != strval):
				self.__notifiers_final[func] = (val[0], val[1], strval, val[3])
				val[1](self)

	# immediate_feedback = True means call notifier on every value CHANGE
	# immediate_feedback = False means call notifier on leave the config element (up/down) when value have CHANGED
	# call_on_save_or_cancel = True means call notifier always on save/cancel.. even when value have not changed
	def addNotifier(self, notifier, initial_call = True, immediate_feedback = True, call_on_save_or_cancel = False):
		assert callable(notifier), "notifiers must be callable"
		try:
			# repr(notifier) is useless for private functions starting with __ 
			key = 'addNotifier {1} <{0} instance at {2}>'.format(notifier.__module__, notifier.__func__, hex(id(notifier.__self__)))
		except:
			key = repr(notifier)
		if immediate_feedback:
			self.__notifiers[key] = (self.key, notifier, str(self.value), call_on_save_or_cancel)
		else:
			self.__notifiers_final[key] = (self.key, notifier, str(self.value), call_on_save_or_cancel)
		self.key += 1
		# CHECKME:
		# do we want to call the notifier
		#  - at all when adding it? (yes, though optional)
		#  - when the default is active? (yes)
		#  - when no value *yet* has been set,
		#    because no config has ever been read (currently yes)
		#    (though that's not so easy to detect.
		#     the entry could just be new.)
		if initial_call:
			notifier(self)

	def removeNotifier(self, notifier):
		try:
			n = 'addNotifier {1} <{0} instance at {2}>'.format(notifier.__module__, notifier.__func__, hex(id(notifier.__self__)))
		except:
			n = repr(notifier)
		if n in self.__notifiers:
			del self.__notifiers[n]
		if n in self.__notifiers_final:
			del self.__notifiers_final[n]

	def clearNotifiers(self):
		self.__notifiers = { }

	def disableSave(self):
		self.save_disabled = True

	def __call__(self, selected):
		return self.getMulti(selected)

	def onSelect(self, session):
		pass

	def onDeselect(self, session):
		self.changedFinal()

KEY_LEFT = 0
KEY_RIGHT = 1
KEY_OK = 2
KEY_DELETE = 3
KEY_BACKSPACE = 4
KEY_HOME = 5
KEY_END = 6
KEY_TOGGLEOW = 7
KEY_ASCII = 8
KEY_TIMEOUT = 9
KEY_NUMBERS = list(range(12, 12+10))
KEY_0 = 12
KEY_9 = 12+9

def getKeyNumber(key):
	assert key in KEY_NUMBERS
	return key - KEY_0

class choicesList(object): # XXX: we might want a better name for this
	LIST_TYPE_LIST = 1
	LIST_TYPE_DICT = 2

	def __init__(self, choices, type = None):
		self.choices = choices
		self.__itemDescriptionUpdatedCallbacks = []

		if type is None:
			if isinstance(choices, list):
				self.type = choicesList.LIST_TYPE_LIST
			elif isinstance(choices, dict):
				self.type = choicesList.LIST_TYPE_DICT
			else:
				assert False, "choices must be dict or list!"
		else:
			self.type = type

	def __list__(self):
		if self.type == choicesList.LIST_TYPE_LIST:
			ret = [not isinstance(x, tuple) and x or x[0] for x in self.choices]
		else:
			ret = list(self.choices.keys())
		return ret or [""]

	def __iter__(self):
		if self.type == choicesList.LIST_TYPE_LIST:
			ret = [not isinstance(x, tuple) and x or x[0] for x in self.choices]
		else:
			ret = self.choices
		return iter(ret or [""])

	def __len__(self):
		return len(self.choices) or 1

	def additemDescriptionUpdatedCallback(self, callback):
		self.__itemDescriptionUpdatedCallbacks.append(callback)

	def updateItemDescription(self, index, descr):
		if self.type == choicesList.LIST_TYPE_LIST:
			orig = self.choices[index]
			assert isinstance(orig, tuple)
			self.choices[index] = (orig[0], descr)
		else:
			key = list(self.choices.keys())[index]
			self.choices[key] = descr
		for cb in self.__itemDescriptionUpdatedCallbacks:
			try:
				cb()
			except:
				from traceback import print_exc
				print("WARNING: callback", cb, "in config.choicesList.__itemDescriptionUpdatedCallbacks throws exception (removing callback):")
				print_exc()
				self.__itemDescriptionUpdatedCallbacks.remove(cb)

	def __getitem__(self, index):
		if self.type == choicesList.LIST_TYPE_LIST:
			ret = self.choices[index]
			if isinstance(ret, tuple):
				ret = ret[0]
			return ret
		return list(self.choices.keys())[index]

	def index(self, value):
		return self.__list__().index(value)

	def __setitem__(self, index, value):
		if self.type == choicesList.LIST_TYPE_LIST:
			orig = self.choices[index]
			if isinstance(orig, tuple):
				self.choices[index] = (value, orig[1])
			else:
				self.choices[index] = value
		else:
			key = list(self.choices.keys())[index]
			orig = self.choices[key]
			del self.choices[key]
			self.choices[value] = orig

	def default(self):
		choices = self.choices
		if not choices:
			return ""
		if self.type is choicesList.LIST_TYPE_LIST:
			default = choices[0]
			if isinstance(default, tuple):
				default = default[0]
		else:
			default = list(choices.keys())[0]
		return default

class descriptionList(choicesList): # XXX: we might want a better name for this
	def __list__(self):
		if self.type == choicesList.LIST_TYPE_LIST:
			ret = [not isinstance(x, tuple) and x or x[1] for x in self.choices]
		else:
			ret = list(self.choices.values())
		return ret or [""]

	def __iter__(self):
		return iter(self.__list__())

	def __getitem__(self, index):
		if self.type == choicesList.LIST_TYPE_LIST:
			for x in self.choices:
				if isinstance(x, tuple):
					if x[0] == index:
						return str(x[1])
				elif x == index:
					return str(x)
			return str(index) # Fallback!
		else:
			return str(self.choices.get(index, ""))

	def __setitem__(self, index, value):
		if self.type == choicesList.LIST_TYPE_LIST:
			i = self.index(index)
			orig = self.choices[i]
			if isinstance(orig, tuple):
				self.choices[i] = (orig[0], value)
			else:
				self.choices[i] = value
		else:
			self.choices[index] = value

#
# ConfigSelection is a "one of.."-type.
# it has the "choices", usually a list, which contains
# (id, desc)-tuples (or just only the ids, in case the id
# will be used as description)
#
# all ids MUST be plain strings.
#
class ConfigSelection(ConfigElement):
	def __init__(self, choices, default = None):
		ConfigElement.__init__(self)
		self.choices = choicesList(choices)
		self.choices.additemDescriptionUpdatedCallback(self._invalidateCachedDescription)

		if default is None:
			default = self.choices.default()

		self._invalidateCachedDescription()
		self.default = self._value = default

	def setChoices(self, choices, default = None):
		self.choices = choicesList(choices)
		self.choices.additemDescriptionUpdatedCallback(self._invalidateCachedDescription)

		if default is None:
			default = self.choices.default()
		self.default = default

		if self.value not in self.choices:
			self.value = default
		self._invalidateCachedDescription()
		self.changed()

	def _invalidateCachedDescription(self):
		self._descr = None

	def getChoices(self):
		return self.choices.choices

	def setValue(self, value):
		if value in self.choices:
			self._value = value
		else:
			self._value = self.default
		self._descr = None
		self.changed()

	def tostring(self, val):
		return val

	def getValue(self):
		return self._value

	def setCurrentText(self, text):
		i = self.choices.index(self.value)
		self.choices[i] = text
		self._descr = self.description[text] = text
		self._value = text

	value = property(getValue, setValue)

	def getIndex(self):
		return self.choices.index(self.value)

	index = property(getIndex)

	# GUI
	def handleKey(self, key):
		nchoices = len(self.choices)
		i = self.choices.index(self.value)
		if key == KEY_LEFT:
			self.value = self.choices[(i + nchoices - 1) % nchoices]
		elif key == KEY_RIGHT:
			self.value = self.choices[(i + 1) % nchoices]
		elif key == KEY_HOME:
			self.value = self.choices[0]
		elif key == KEY_END:
			self.value = self.choices[nchoices - 1]

	def selectNext(self):
		nchoices = len(self.choices)
		i = self.choices.index(self.value)
		self.value = self.choices[(i + 1) % nchoices]

	def getText(self):
		if self._descr is not None:
			return self._descr
		descr = self._descr = self.description[self.value]
		if descr:
			return _(descr)
		return descr

	def getMulti(self, selected):
		if self._descr is not None:
			descr = self._descr
		else:
			descr = self._descr = self.description[self.value]
		if descr:
			return ("text", _(descr))
		return ("text", descr)

	# HTML
	def getHTML(self, id):
		res = ""
		for v in self.choices:
			descr = self.description[v]
			if self.value == v:
				checked = 'checked="checked" '
			else:
				checked = ''
			res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + descr + "</input></br>\n"
		return res;
		
	#dre: return a drop down instead of two radio buttons
	def getSelectionHTML(self, id, classname="", skipList = [], disabled="", jsfunc="", hidden="0", cat=""):
		display = ""
		if hidden == "1":
			display = 'style="display:None;"'
		res = '<select class="' + classname + '" name="' + id + '" ' + disabled + ' ' + jsfunc + ' ' + display + ' id="' + cat + '">'
		for v in self.choices:
			if v in skipList:
				continue
			descr = self.description[v]
			if descr:
				descr = _(descr)
			if self.value == v:
				selected = 'selected="selected" '
			else:
				selected = ''
			res += '<option value="' + v + '" ' + selected + '>' + descr + '</option>'
		res += '</select>'
		return res
	#dre: end

	def unsafeAssign(self, value):
		# setValue does check if value is in choices. This is safe enough.
		self.value = value

	description = property(lambda self: descriptionList(self.choices.choices, self.choices.type))

# a binary decision.
#
# several customized versions exist for different
# descriptions.
#
boolean_descriptions = {False: "false", True: "true"}
class ConfigBoolean(ConfigElement):
	_onOffPixmaps = {}
	@staticmethod
	def setOnOffPixmaps(onPixmap, offPixmap):
		ConfigBoolean._onOffPixmaps = {
				True : onPixmap,
				False : offPixmap
			}

	def __init__(self, default = False, descriptions = boolean_descriptions):
		ConfigElement.__init__(self)
		self.descriptions = descriptions
		self.value = self.default = default

	def handleKey(self, key):
		if key in (KEY_LEFT, KEY_RIGHT):
			self.value = not self.value
		elif key == KEY_HOME:
			self.value = False
		elif key == KEY_END:
			self.value = True

	def getText(self):
		descr = self.descriptions[self.value]
		if descr:
			return _(descr)
		return descr

	def getMulti(self, selected):
		if ConfigBoolean._onOffPixmaps:
			return ("pixmap", ConfigBoolean._onOffPixmaps[self.value])
		descr = self.descriptions[self.value]
		if descr:
			return ("text", _(descr))
		return ("text", descr)

	def tostring(self, value):
		if not value:
			return "false"
		else:
			return "true"

	def fromstring(self, val):
		if val == "true":
			return True
		else:
			return False

	def getHTML(self, id):
		if self.value:
			checked = ' checked="checked"'
		else:
			checked = ''
		return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
	
	#dre: return a drop down instead of two radio buttons
	def getSelectionHTML(self, id, classname="", skipList = [], disabled="", jsfunc=""):
		res = '<select class="' + classname + '" name="' + id + '" ' + disabled + ' ' + jsfunc + ' id="' + id + '_select">'
		for v in self.descriptions:
			if v in skipList:
				continue
			descr = self.descriptions[v]
			if descr:
				descr = _(descr)
			if self.value == v:
				selected = 'selected="selected" '
			else:
				selected = ''
			res += '<option value="' + str(v) + '" ' + selected + '>' + str(descr) + '</option>'
		res += '</select>'
		return res
	#dre: end

	# this is FLAWED. and must be fixed.
	def unsafeAssign(self, value):
		if value == "1":
			self.value = True
		else:
			self.value = False

yes_no_descriptions = {False: _("no"), True: _("yes")}
class ConfigYesNo(ConfigBoolean):
	def __init__(self, default = False):
		ConfigBoolean.__init__(self, default = default, descriptions = yes_no_descriptions)

on_off_descriptions = {False: _("off"), True: _("on")}
class ConfigOnOff(ConfigBoolean):
	def __init__(self, default = False):
		ConfigBoolean.__init__(self, default = default, descriptions = on_off_descriptions)

class ConfigEnableDisable(ConfigOnOff):
	def __init__(self, default = False):
		print("WARNING! ConfigEnableDisable is deprecated, please use ConfigOnOff instead!")
		ConfigOnOff.__init__(self, default = default)

class ConfigDateTime(ConfigElement):
	def __init__(self, default, formatstring, increment = 86400):
		ConfigElement.__init__(self)
		self.increment = increment
		self.formatstring = formatstring
		self.value = self.default = int(default)

	def handleKey(self, key):
		if key == KEY_LEFT:
			self.value = self.value - self.increment
		elif key == KEY_RIGHT:
			self.value = self.value + self.increment
		elif key == KEY_HOME or key == KEY_END:
			self.value = self.default

	def getText(self):
		return strftime(self.formatstring, localtime(self.value))

	def getMulti(self, selected):
		return ("text", strftime(self.formatstring, localtime(self.value)))

	def fromstring(self, val):
		return int(val)

# *THE* mighty config element class
#
# allows you to store/edit a sequence of values.
# can be used for IP-addresses, dates, plain integers, ...
# several helper exist to ease this up a bit.
#
class ConfigSequence(ConfigElement):
	def __init__(self, seperator, limits, default, censor_char = ""):
		ConfigElement.__init__(self)
		assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
		assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
		#assert isinstance(default, list), "default must be a list"
		#assert isinstance(default[0], int), "list must contain numbers"
		#assert len(default) == len(limits), "length must match"

		self.marked_pos = 0
		self.seperator = seperator
		self.limits = limits
		self.censor_char = censor_char

		self.default = default
		self.value = copy_copy(default)
		self.endNotifier = None

	def validate(self):
		max_pos = 0
		num = 0
		for i in self._value:
			max_pos += len(str(self.limits[num][1]))

			if self._value[num] < self.limits[num][0]:
				self._value[num] = self.limits[num][0]

			if self._value[num] > self.limits[num][1]:
				self._value[num] = self.limits[num][1]

			num += 1

		if self.marked_pos >= max_pos:
			if self.endNotifier:
				for x in self.endNotifier:
					x(self)
			self.marked_pos = max_pos - 1

		if self.marked_pos < 0:
			self.marked_pos = 0

	def validatePos(self):
		if self.marked_pos < 0:
			self.marked_pos = 0

		total_len = sum([len(str(x[1])) for x in self.limits])

		if self.marked_pos >= total_len:
			self.marked_pos = total_len - 1

	def addEndNotifier(self, notifier):
		if self.endNotifier is None:
			self.endNotifier = []
		self.endNotifier.append(notifier)

	def handleKey(self, key):
		if key == KEY_LEFT:
			self.marked_pos -= 1
			self.validatePos()

		elif key == KEY_RIGHT:
			self.marked_pos += 1
			self.validatePos()

		elif key == KEY_HOME:
			self.marked_pos = 0
			self.validatePos()

		elif key == KEY_END:
			max_pos = 0
			num = 0
			for i in self._value:
				max_pos += len(str(self.limits[num][1]))
				num += 1
			self.marked_pos = max_pos - 1
			self.validatePos()

		elif key in KEY_NUMBERS or key == KEY_ASCII:
			if key == KEY_ASCII:
				code = getPrevAsciiCode()
				if code < 48 or code > 57:
					return
				number = code - 48
			else:
				number = getKeyNumber(key)

			block_len = [len(str(x[1])) for x in self.limits]

			pos = 0
			blocknumber = 0
			block_len_total = [0, ]
			for x in block_len:
				pos += block_len[blocknumber]
				block_len_total.append(pos)
				if pos - 1 >= self.marked_pos:
					pass
				else:
					blocknumber += 1

			# length of numberblock
			number_len = len(str(self.limits[blocknumber][1]))

			# position in the block
			posinblock = self.marked_pos - block_len_total[blocknumber]

			oldvalue = self._value[blocknumber]
			olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
			newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)

			self._value[blocknumber] = newvalue
			self.marked_pos += 1

			self.validate()
			self.changed()

	def genText(self):
		value = ""
		mPos = self.marked_pos
		num = 0;
		for i in self._value:
			if value:	#fixme no heading separator possible
				value += self.seperator
				if mPos >= len(value) - 1:
					mPos += 1
			if self.censor_char == "":
				value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
			else:
				value += (self.censor_char * len(str(self.limits[num][1])))
			num += 1
		return (value, mPos)

	def getText(self):
		(value, mPos) = self.genText()
		return value

	def getMulti(self, selected):
		(value, mPos) = self.genText()
			# only mark cursor when we are selected
			# (this code is heavily ink optimized!)
		if self.enabled:
			return ("mtext"[1-selected:], value, [mPos])
		else:
			return ("text", value)

	def tostring(self, val):
		return self.seperator.join([self.saveSingle(x) for x in val])

	def saveSingle(self, v):
		return str(v)

	def fromstring(self, value):
		try:
			return [int(x) for x in value.split(self.seperator)]
		except:
			return self.default
	
	#dre: added getHTML	
	def getHTML(self, id, classname=""):
		length = len(str(self.limits[0][1]))
		return '<input type="text" class="' + classname + '" name="' + id + '" value="' + str(self.value) + '" size="' + str(length) + '" maxlength="' + str(length) + '"/>'
	#dre

ip_limits = [(0,255),(0,255),(0,255),(0,255)]
class ConfigIP(ConfigSequence):
	def __init__(self, default, auto_jump = False):
		ConfigSequence.__init__(self, seperator = ".", limits = ip_limits, default = default)
		self.block_len = [len(str(x[1])) for x in self.limits]
		self.marked_block = 0
		self.overwrite = True
		self.auto_jump = auto_jump

	def handleKey(self, key):
		if key == KEY_LEFT:
			if self.marked_block > 0:
				self.marked_block -= 1
			self.overwrite = True

		elif key == KEY_RIGHT:
			if self.marked_block < len(self.limits)-1:
				self.marked_block += 1
			self.overwrite = True

		elif key == KEY_HOME:
			self.marked_block = 0
			self.overwrite = True

		elif key == KEY_END:
			self.marked_block = len(self.limits)-1
			self.overwrite = True

		elif key in KEY_NUMBERS or key == KEY_ASCII:
			if key == KEY_ASCII:
				code = getPrevAsciiCode()
				if code < 48 or code > 57:
					return
				number = code - 48
			else:
				number = getKeyNumber(key)
			oldvalue = self._value[self.marked_block]

			if self.overwrite:
				self._value[self.marked_block] = number
				self.overwrite = False
			else:
				oldvalue *= 10
				newvalue = oldvalue + number
				if self.auto_jump and newvalue > self.limits[self.marked_block][1] and self.marked_block < len(self.limits)-1:
					self.handleKey(KEY_RIGHT)
					self.handleKey(key)
					return
				else:
					self._value[self.marked_block] = newvalue

			if len(str(self._value[self.marked_block])) >= self.block_len[self.marked_block]:
				self.handleKey(KEY_RIGHT)

			self.validate()
			self.changed()

	def genText(self):
		value = ""
		block_strlen = []
		for i in self._value:
			block_strlen.append(len(str(i)))
			if value:
				value += self.seperator
			value += str(i)
		leftPos = sum(block_strlen[:(self.marked_block)])+self.marked_block
		rightPos = sum(block_strlen[:(self.marked_block+1)])+self.marked_block
		mBlock = list(range(leftPos, rightPos))
		return (value, mBlock)

	def getMulti(self, selected):
		(value, mBlock) = self.genText()
		if self.enabled:
			return ("mtext"[1-selected:], value, mBlock)
		else:
			return ("text", value)

	def getHTML(self, id):
		# we definitely don't want leading zeros
		return '.'.join(["%d" % d for d in self.value])

mac_limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)]
class ConfigMAC(ConfigSequence):
	def __init__(self, default):
		ConfigSequence.__init__(self, seperator = ":", limits = mac_limits, default = default)

class ConfigPosition(ConfigSequence):
	def __init__(self, default, args):
		ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)

clock_limits = [(0,23),(0,59)]
class ConfigClock(ConfigSequence):
	def __init__(self, default):
		t = localtime(default)
		ConfigSequence.__init__(self, seperator = ":", limits = clock_limits, default = [t.tm_hour, t.tm_min])

	def increment(self):
		# Check if Minutes maxed out
		if self._value[1] == 59:
			# Increment Hour, reset Minutes
			if self._value[0] < 23:
				self._value[0] += 1
			else:
				self._value[0] = 0
			self._value[1] = 0
		else:
			# Increment Minutes
			self._value[1] += 1
		# Trigger change
		self.changed()

	def decrement(self):
		# Check if Minutes is minimum
		if self._value[1] == 0:
			# Decrement Hour, set Minutes to 59
			if self._value[0] > 0:
				self._value[0] -= 1
			else:
				self._value[0] = 23
			self._value[1] = 59
		else:
			# Decrement Minutes
			self._value[1] -= 1
		# Trigger change
		self.changed()

integer_limits = (0, 9999999999)
class ConfigInteger(ConfigSequence):
	def __init__(self, default, limits = integer_limits):
		ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)

	# you need to override this to do input validation
	def setValue(self, value):
		self._value = [int(value)]
		self.changed()

	def getValue(self):
		return self._value[0]

	value = property(getValue, setValue)

	def fromstring(self, value):
		return int(value)

	def tostring(self, value):
		return str(value)

class ConfigPIN(ConfigInteger):
	def __init__(self, default, len = 4, censor = ""):
		assert isinstance(default, int), "ConfigPIN default must be an integer"
		ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
		self.len = len

	def getLength(self):
		return self.len

class ConfigFloat(ConfigSequence):
	def __init__(self, default, limits):
		ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)

	def getFloat(self):
		return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])

	float = property(getFloat)

# an editable text...
class ConfigTextBase(ConfigElement):
	def __init__(self, default = "", fixed_size = True, visible_width = False, censor_char = ''):
		ConfigElement.__init__(self)
		self.selected = False
		self.censor_char = censor_char
		self.marked_pos = 0
		self.allmarked = (default != "")
		self.fixed_size = fixed_size
		self.visible_width = visible_width
		self.offset = 0
		self.overwrite = fixed_size
		self.help_window = None
		self.value = self.default = default
		self._keyboardMode = 0

	def validateMarker(self):
		textlen = len(self.text)
		if self.fixed_size:
			if self.marked_pos > textlen-1:
				self.marked_pos = textlen-1
		else:
			if self.marked_pos > textlen:
				self.marked_pos = textlen
		if self.marked_pos < 0:
			self.marked_pos = 0
		if self.visible_width:
			if self.marked_pos < self.offset:
				self.offset = self.marked_pos
			if self.marked_pos >= self.offset + self.visible_width:
				if self.marked_pos == textlen:
					self.offset = self.marked_pos - self.visible_width
				else:
					self.offset = self.marked_pos - self.visible_width + 1
			if self.offset > 0 and self.offset + self.visible_width > textlen:
				self.offset = max(0, textlen - self.visible_width)

	def insertChar(self, ch, pos, owr):
		if owr or self.overwrite:
			self.text = self.text[0:pos] + ch + self.text[pos + 1:]
		elif self.fixed_size:
			self.text = self.text[0:pos] + ch + self.text[pos:-1]
		else:
			self.text = self.text[0:pos] + ch + self.text[pos:]

	def deleteChar(self, pos):
		if not self.fixed_size:
			self.text = self.text[0:pos] + self.text[pos + 1:]
		elif self.overwrite:
			self.text = self.text[0:pos] + " " + self.text[pos + 1:]
		else:
			self.text = self.text[0:pos] + self.text[pos + 1:] + " "

	def deleteAllChars(self):
		if self.fixed_size:
			self.text = " " * len(self.text)
		else:
			self.text = ""
		self.marked_pos = 0

	def handleKey(self, key):
		# this will no change anything on the value itself
		# so we can handle it here in gui element
		if key == KEY_DELETE:
			self.timeout()
			if self.allmarked:
				self.deleteAllChars()
				self.allmarked = False
			else:
				self.deleteChar(self.marked_pos)
				if self.fixed_size and self.overwrite:
					self.marked_pos += 1
		elif key == KEY_BACKSPACE:
			self.timeout()
			if self.allmarked:
				self.deleteAllChars()
				self.allmarked = False
			elif self.marked_pos > 0:
				self.deleteChar(self.marked_pos-1)
				if not self.fixed_size and self.offset > 0:
					self.offset -= 1
				self.marked_pos -= 1
		elif key == KEY_LEFT:
			self.timeout()
			if self.allmarked:
				self.marked_pos = len(self.text)
				self.allmarked = False
			else:
				self.marked_pos -= 1
		elif key == KEY_RIGHT:
			self.timeout()
			if self.allmarked:
				self.marked_pos = 0
				self.allmarked = False
			else:
				self.marked_pos += 1
		elif key == KEY_HOME:
			self.timeout()
			self.allmarked = False
			self.marked_pos = 0
		elif key == KEY_END:
			self.timeout()
			self.allmarked = False
			self.marked_pos = len(self.text)
		elif key == KEY_TOGGLEOW:
			self.timeout()
			self.overwrite = not self.overwrite
		elif key == KEY_ASCII:
			self.timeout()
			newChar = unichr(getPrevAsciiCode())
			if not self.useableChars or newChar in self.useableChars:
				if self.allmarked:
					self.deleteAllChars()
					self.allmarked = False
				self.insertChar(newChar, self.marked_pos, False)
				self.marked_pos += 1
		elif key in KEY_NUMBERS:
			owr = self.lastKey == getKeyNumber(key)
			newChar = self.getKey(getKeyNumber(key))
			if self.allmarked:
				self.deleteAllChars()
				self.allmarked = False
			self.insertChar(newChar, self.marked_pos, owr)
		elif key == KEY_TIMEOUT:
			self.timeout()
			if self.help_window:
				self.help_window.update(self)
			return

		if self.help_window:
			self.help_window.update(self)
		self.validateMarker()
		self.changed()

	def nextFunc(self):
		self.marked_pos += 1
		self.validateMarker()
		self.changed()

	def getValue(self):
		return six.ensure_str(self.text)

	def setValue(self, val):
		try:
			self.text = six.ensure_text(val)
		except UnicodeDecodeError:
			self.text = six.ensure_text(val, errors='ignore')
			print("Broken UTF8!")
		self.changed()

	value = property(getValue, setValue)
	_value = property(getValue, setValue)

	def genText(self):
		tlen = len(self.text)
		if tlen and self.censor_char != '':
			tmp = [ self.censor_char for c in range(tlen) ]
			if self.selected:
				mpos = self.marked_pos
				if mpos >= tlen:
					mpos -= 1
				tmp[mpos] = self.text[mpos]
			text = u''.join(tmp)
		else:
			text = self.text
		return text

	def getText(self):
		return self.genText()

	def getMulti(self, selected):
		text = self.genText()
		if self.visible_width:
			if self.allmarked:
				mark = list(range(0, min(self.visible_width, len(text))))
			else:
				mark = [self.marked_pos-self.offset]
			return ("mtext"[1-selected:], six.ensure_str(text[self.offset:self.offset+self.visible_width])+" ", mark)
		else:
			if self.allmarked:
				mark = list(range(0, len(text)))
			else:
				mark = [self.marked_pos]
			return ("mtext"[1-selected:], six.ensure_str(text)+" ", mark)

	def onSelect(self, session):
		if not self.enabled:
			self.allmarked = False
			self.marked_pos = -1
			return
		self.selected = True
		self.allmarked = (self.value != "")
		self._keyboardMode = eRCInput.getInstance().getKeyboardMode()
		eRCInput.getInstance().setKeyboardMode(eRCInput.kmAscii)
		if session is not None:
			from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
			self.help_window = session.instantiateDialog(NumericalTextInputHelpDialog, self, zPosition=5000)
			self.help_window.neverAnimate()
			self.help_window.show()
		else:
			Log.w("Help dialog skipped - session is None!")

	def onDeselect(self, session):
		self.selected = False
		eRCInput.getInstance().setKeyboardMode(self._keyboardMode)
		self.marked_pos = 0
		self.offset = 0
		if self.help_window:
			session.deleteDialog(self.help_window)
			self.help_window = None
		ConfigElement.onDeselect(self, session)

	#dre: fix bug in dmm's code. self.value can also be an integer, add classname
	def getHTML(self, id, classname=""):
		return '<input type="text" class="' + classname + '" name="' + id + '" value="' + str(self.value) + '" /><br>\n'
	#dre: end

	def unsafeAssign(self, value):
		self.value = str(value)

class ConfigText(ConfigTextBase, NumericalTextInput):
	def __init__(self, default = "", fixed_size = True, visible_width = False, censor_char = ''):
		ConfigTextBase.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width, censor_char = censor_char)
		NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)

class ConfigHexSequence(ConfigTextBase, NumericalHexInput):
	def __init__(self, default="000000", fixed_size = True, visible_width = False, censor_char = ''):
		ConfigTextBase.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
		NumericalHexInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)

#IPv6 Address with validation and autoformatting
class ConfigIP6(ConfigTextBase, NumericalHexInput):
	def __init__(self, default = "::", fixed_size=False, visible_width=False):
		ConfigTextBase.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
		NumericalHexInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)

	def isValid(self):
		try:
			ip = IPAddress(self.text)
			return ip.version == 6
		except ValueError:
			Log.w("%s is no valid v6 IP" %self.text)
			return False

	def getValue(self):
		if not self.isValid():
			self._setDefault(force=True)
		return self.getText()

	def setValue(self, val):
		try:
			val = six.ensure_text(val)
			self.text = IPAddress(val).format()
		except:
			Log.w("No valid IPv6 Address")
			self._setDefault(force=True)
		self.changed()

	def _setDefault(self, force=False):
		if not self.text or force:
			self.text = self.default

	def getText(self):
		return self.text

	def onDeselect(self, session):
		self.setValue(self.text)
		ConfigTextBase.onDeselect(self, session)

class ConfigPassword(ConfigText):
	def __init__(self, default = "", fixed_size = False, visible_width = False, censor = "*"):
		ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width, censor_char = censor)

# lets the user select between [min, min+stepwidth, min+(stepwidth*2)..., maxval] with maxval <= max depending
# on the stepwidth
# min, max, stepwidth, default are int values
# wraparound: pressing RIGHT key at max value brings you to min value and vice versa if set to True
class ConfigSelectionNumber(ConfigSelection):
	def __init__(self, min, max, stepwidth, default = None, wraparound = False):
		self.wraparound = wraparound
		if default is None:
			default = min
		default = str(default)
		choices = []
		step = min
		while step <= max:
			choices.append(str(step))
			step += stepwidth
		
		ConfigSelection.__init__(self, choices, default)

	def getValue(self):
		return int(ConfigSelection.getValue(self))

	def setValue(self, val):
		ConfigSelection.setValue(self, str(val))

	def handleKey(self, key):
		if not self.wraparound:
			if key == KEY_RIGHT:
				if len(self.choices) == (self.choices.index(self.value) + 1):
					return
			if key == KEY_LEFT:
				if self.choices.index(self.value) == 0:
					return
		ConfigSelection.handleKey(self, key)
		
	#dre: return a drop down
	def getSelectionHTML(self, id, classname="", skipList = [], disabled="", jsfunc = ""):
		res = '<select class="' + classname + '" name="' + id + '" ' + disabled + ' ' + jsfunc + ' >'
		for v in self.choices:
			if v in skipList:
				continue
		#descr = self.descriptions[v]
		#if descr:
		#descr = _(descr)
			if self.value == v:
				selected = 'selected="selected" '
			else:
				selected = ''
			res += '<option value="' + str(v) + '" ' + selected + '>' + str(v) + '</option>'
		res += '</select>'
		return res
	#dre: end

class ConfigNumber(ConfigText):
	def __init__(self, default = 0):
		ConfigText.__init__(self, str(default), fixed_size = False)

	def getValue(self):
		return int(self.text)

	def setValue(self, val):
		self.text = str(val)
		self.changed()

	value = property(getValue, setValue)
	_value = property(getValue, setValue)

	def isChanged(self):
		sv = self.saved_value
		strv = self.tostring(self.value)
		if sv is None and strv == self.default:
			return False
		return strv != sv

	def conform(self):
		pos = len(self.text) - self.marked_pos
		self.text = self.text.lstrip("0")
		if self.text == "":
			self.text = "0"
		if pos > len(self.text):
			self.marked_pos = 0
		else:
			self.marked_pos = len(self.text) - pos

	def handleKey(self, key):
		if key in KEY_NUMBERS or key == KEY_ASCII:
			if key == KEY_ASCII:
				ascii = getPrevAsciiCode()
				if not (48 <= ascii <= 57):
					return
			else:
				ascii = getKeyNumber(key) + 48
			newChar = unichr(ascii)
			if self.allmarked:
				self.deleteAllChars()
				self.allmarked = False
			self.insertChar(newChar, self.marked_pos, False)
			self.marked_pos += 1
		else:
			ConfigText.handleKey(self, key)
		self.conform()

	def onSelect(self, session):
		self.allmarked = (self.value != "")
		self._keyboardMode = eRCInput.getInstance().getKeyboardMode()

class ConfigSearchText(ConfigText):
	def __init__(self, default = "", fixed_size = False, visible_width = False, special_chars = ""):
		ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
		NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False, search = special_chars)

class ConfigDirectory(ConfigText):
	def __init__(self, default="", visible_width=60):
		ConfigText.__init__(self, default, fixed_size = True, visible_width = visible_width)

	def handleKey(self, key):
		pass

	def getValue(self):
		if self.text == "":
			return None
		else:
			return ConfigText.getValue(self)

	def setValue(self, val):
		if val == None:
			val = ""
		ConfigText.setValue(self, val)

	def getMulti(self, selected):
		if self.text == "":
			return ("mtext"[1-selected:], _("List of Storage Devices"), list())
		else:
			return ConfigText.getMulti(self, selected)

	def onSelect(self, session):
		self.allmarked = (self.value != "")
		self._keyboardMode = eRCInput.getInstance().getKeyboardMode()

# a slider.
class ConfigSlider(ConfigElement):
	def __init__(self, default = 0, increment = 1, limits = (0, 100)):
		ConfigElement.__init__(self)
		self.value = self.default = default
		self.min = limits[0]
		self.max = limits[1]
		self.increment = increment

	def checkValues(self):
		if self.value < self.min:
			self.value = self.min

		if self.value > self.max:
			self.value = self.max

	def handleKey(self, key):
		if key == KEY_LEFT:
			self.value -= self.increment
		elif key == KEY_RIGHT:
			self.value += self.increment
		elif key == KEY_HOME:
			self.value = self.min
		elif key == KEY_END:
			self.value = self.max
		else:
			return
		self.checkValues()

	def getText(self):
		return "%d / %d" % (self.value, self.max)

	def getMulti(self, selected):
		self.checkValues()
		return ("slider", self.value, self.max)

	def fromstring(self, value):
		return int(value)
		
	#dre: return a drop down
	def getSelectionHTML(self, id, classname="", skipList = [], disabled="", jsfunc = ""):
		res = '<select class="' + classname + '" name="' + id + '" ' + disabled + ' ' + jsfunc + ' >'
		for v in range(self.min, self.max+self.increment, self.increment):
			if v in skipList:
				continue
			if self.value == v:
				selected = 'selected="selected" '
			else:
				selected = ''
			res += '<option value="' + str(v) + '" ' + selected + '>' + str(v) + '</option>'
		res += '</select>'
		return res
	#dre: end

# a satlist. in fact, it's a ConfigSelection.
class ConfigSatlist(ConfigSelection):
	def __init__(self, list, default = None):
		if default is not None:
			default = str(default)
		ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)

	def getOrbitalPosition(self):
		if self.value == "":
			return None
		return int(self.value)

	orbital_position = property(getOrbitalPosition)

class ConfigSet(ConfigElement):
	def __init__(self, choices, default = [], resort=True):
		ConfigElement.__init__(self)
		self.resort = resort
		if isinstance(choices, list):
			if resort:
				choices.sort()
			self.choices = choicesList(choices, choicesList.LIST_TYPE_LIST)
		else:
			assert False, "ConfigSet choices must be a list!"
		if default is None:
			default = []
		self.pos = -1
		if resort:
			default.sort()
		self.default = default
		self.help_window = None
		self.value = default[:]
		self.onSelectedIndexChanged = []

	def toggleChoice(self, choice):
		value = self.value
		if choice in value:
			value.remove(choice)
		else:
			value.append(choice)
			if self.resort:
				value.sort()
		self.changed()

	def handleKey(self, key):
		if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE, KEY_OK]:
			if self.pos != -1:
				self.toggleChoice(self.choices[self.pos])
		elif key == KEY_LEFT:
			if self.pos < 0:
				self.pos = len(self.choices)-1
			else:
				self.pos -= 1
		elif key == KEY_RIGHT:
			if self.pos >= len(self.choices)-1:
				self.pos = -1
			else:
				self.pos += 1
		elif key in (KEY_HOME, KEY_END):
			self.pos = -1
		for fnc in self.onSelectedIndexChanged:
			fnc(self.pos)

	def genString(self, lst):
		res = ""
		for x in lst:
			res += self.description[x]+" "
		return res

	def getText(self):
		return self.genString(self.value)

	def getMulti(self, selected):
		if not selected or self.pos == -1:
			return ("text", self.genString(self.value))
		else:
			tmp = self.value[:]
			ch = self.choices[self.pos]
			mem = ch in self.value
			if not mem:
				tmp.append(ch)
				if self.resort:
					tmp.sort()
			ind = tmp.index(ch)
			val1 = self.genString(tmp[:ind])
			val2 = " "+self.genString(tmp[ind+1:])
			if mem:
				chstr = " "+self.description[ch]+" "
			else:
				chstr = "("+self.description[ch]+")"
			len_val1 = len(val1)
			return ("mtext", val1+chstr+val2, list(range(len_val1, len_val1 + len(chstr))))


	def onSelect(self, session):
		if session is not None:
			from Screens.ConfigSetHelpDialog import ConfigSetHelpDialog
			self.help_window = session.instantiateDialog(ConfigSetHelpDialog, self, zPosition=5000)
			self.help_window.neverAnimate()
			self.help_window.show()
		else:
			Log.w("Help dialog skipped - session is None!")

	def onDeselect(self, session):
		self.pos = -1
		if self.help_window:
			session.deleteDialog(self.help_window)
			self.help_window = None
		ConfigElement.onDeselect(self, session)

	def tostring(self, value):
		return str(value)

	def fromstring(self, val):
		try:
			return literal_eval(val)
		except:
			return self.default
		
	#dre: return a drop down instead of two radio buttons
	#todo: expand to n (length of default) dropdowns oder evtl. nur checkboxen
	def getSelectionHTML(self, id, classname="", skipList = []):
		#res = '<select class="' + classname + '" name="' + id + '" >'
		i=0
		j=0
		res = ''
	
		for v in self.description:
			if v in skipList:
				continue
			descr = self.description[v]
			if descr:
				descr = _(descr)
			defaultlength = self.getDefaultLength()
			if j < defaultlength:
				if self.value[j] == v:
					checked = 'checked="checked" '
					j = j+1
				else:
					checked = ''
			else:
				checked = ''
			#res += '<option value="' + str(v) + '" ' + selected + '>' + str(descr) + '</option>'
			if i%3 == 0 and i > 0:
				res += '<input type="checkbox" class="' + classname + '" name="' + id + '" value="' + str(v) + '" ' + checked + ' onclick="checkMaxSelection(this,' + str(defaultlength) + ')">' + str(descr) + '<br>'
			else:
				res += '<input type="checkbox" class="' + classname + '" name="' + id + '" value="' + str(v) + '" ' + checked + ' onclick="checkMaxSelection(this,' + str(defaultlength) + ')">' + str(descr) + '&nbsp;'
			i = i+1
		return res
	#dre: end
	
	def getDefaultLength(self):
		return len(self.default)		

	description = property(lambda self: descriptionList(self.choices.choices, choicesList.LIST_TYPE_LIST))

class ConfigLocations(ConfigElement):
	def __init__(self, default = [], visible_width = False):
		ConfigElement.__init__(self)
		self.visible_width = visible_width
		self.pos = -1
		self.default = default
		self.locations = []
		self.mountpoints = []
		self.value = default[:]

	def setValue(self, value):
		locations = self.locations
		loc = [x[0] for x in locations if x[3]]
		add = [x for x in value if not x in loc]
		diff = add + [x for x in loc if not x in value]
		locations = [x for x in locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
		locations.sort(key = lambda x: x[0])
		self.locations = locations
		self.changed()

	def getValue(self):
		self.checkChangedMountpoints()
		locations = self.locations
		for x in locations:
			x[3] = x[2]
		return [x[0] for x in locations if x[3]]

	value = property(getValue, setValue)

	def tostring(self, value):
		return str(value)

	def fromstring(self, val):
		return literal_eval(val)

	def load(self):
		sv = self.saved_value
		if not sv:
			tmp = self.default
		else:
			tmp = self.fromstring(sv)
		locations = [[x, None, False, False] for x in tmp]
		self.refreshMountpoints()
		for x in locations:
			if fileExists(x[0]):
				x[1] = self.getMountpoint(x[0])
				x[2] = True
		self.locations = locations

	def save(self):
		locations = self.locations
		if self.save_disabled or not locations:
			self.saved_value = None
		else:
			self.saved_value = self.tostring([x[0] for x in locations])

	def isChanged(self):
		sv = self.saved_value
		locations = self.locations
		if sv is None and not locations:
			return False
		return self.tostring([x[0] for x in locations]) != sv

	def addedMount(self, mp):
		for x in self.locations:
			if x[1] == mp:
				x[2] = True
			elif x[1] == None and fileExists(x[0]):
				x[1] = self.getMountpoint(x[0])
				x[2] = True

	def removedMount(self, mp):
		for x in self.locations:
			if x[1] == mp:
				x[2] = False

	def refreshMountpoints(self):
		from Components.Harddisk import harddiskmanager
		self.mountpoints = [p.mountpoint for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
		self.mountpoints.sort(key = lambda x: -len(x))

	def checkChangedMountpoints(self):
		oldmounts = self.mountpoints
		self.refreshMountpoints()
		newmounts = self.mountpoints
		if oldmounts == newmounts:
			return
		for x in oldmounts:
			if not x in newmounts:
				self.removedMount(x)
		for x in newmounts:
			if not x in oldmounts:
				self.addedMount(x)

	def getMountpoint(self, file):
		file = os_path.realpath(file)+"/"
		for m in self.mountpoints:
			if file.startswith(m):
				return m
		return None

	def handleKey(self, key):
		if key == KEY_LEFT:
			self.pos -= 1
			if self.pos < -1:
				self.pos = len(self.value)-1
		elif key == KEY_RIGHT:
			self.pos += 1
			if self.pos >= len(self.value):
				self.pos = -1
		elif key in (KEY_HOME, KEY_END):
			self.pos = -1

	def getText(self):
		return " ".join(self.value)

	def getMulti(self, selected):
		if not selected:
			valstr = " ".join(self.value)
			if self.visible_width and len(valstr) > self.visible_width:
				return ("text", valstr[0:self.visible_width])
			else:
				return ("text", valstr)
		else:
			i = 0
			valstr = ""
			ind1 = 0
			ind2 = 0
			for val in self.value:
				if i == self.pos:
					ind1 = len(valstr)
				valstr += str(val)+" "
				if i == self.pos:
					ind2 = len(valstr)
				i += 1
			if self.visible_width and len(valstr) > self.visible_width:
				if ind1+1 < self.visible_width//2:
					off = 0
				else:
					off = min(ind1+1-self.visible_width//2, len(valstr)-self.visible_width)
				return ("mtext", valstr[off:off+self.visible_width], list(range(ind1-off,ind2-off)))
			else:
				return ("mtext", valstr, list(range(ind1,ind2)))

	def onDeselect(self, session):
		self.pos = -1
		ConfigElement.onDeselect(self, session)

# nothing.
class ConfigNothing(ConfigSelection):
	def __init__(self):
		ConfigSelection.__init__(self, choices = [("","")])

# until here, 'saved_value' always had to be a *string*.
# now, in ConfigSubsection, and only there, saved_value
# is a dict, essentially forming a tree.
#
# config.foo.bar=True
# config.foobar=False
#
# turns into:
# config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
#

class ConfigSubsectionContent(object):
	pass

# we store a backup of the loaded configuration
# data in self.stored_values, to be able to deploy
# them when a new config element will be added,
# so non-default values are instantly available

# A list, for example:
# config.dipswitches = ConfigSubList()
# config.dipswitches.append(ConfigYesNo())
# config.dipswitches.append(ConfigYesNo())
# config.dipswitches.append(ConfigYesNo())
class ConfigSubList(list, object):
	def __init__(self):
		list.__init__(self)
		self.stored_values = {}

	def save(self):
		for x in self:
			x.save()

	def load(self):
		for x in self:
			x.load()

	def getSavedValue(self):
		res = { }
		for i, val in enumerate(self):
			sv = val.saved_value
			if sv is not None:
				res[str(i)] = sv
		return res

	def setSavedValue(self, values):
		self.stored_values = dict(values)
		for (key, val) in self.stored_values.items():
			if int(key) < len(self):
				self[int(key)].saved_value = val

	saved_value = property(getSavedValue, setSavedValue)

	def append(self, item):
		i = str(len(self))
		list.append(self, item)
		if i in self.stored_values:
			item.saved_value = self.stored_values[i]
			item.load()

	def dict(self):
		return dict([(str(index), value) for index, value in enumerate(self)])

# same as ConfigSubList, just as a dictionary.
# care must be taken that the 'key' has a proper
# str() method, because it will be used in the config
# file.
class ConfigSubDict(dict, object):
	def __init__(self):
		dict.__init__(self)
		self.stored_values = {}

	def save(self):
		for x in self.values():
			x.save()

	def load(self):
		for x in self.values():
			x.load()

	def getSavedValue(self):
		res = {}
		for (key, val) in self.items():
			sv = val.saved_value
			if sv is not None:
				res[str(key)] = sv
		return res

	def setSavedValue(self, values):
		self.stored_values = dict(values)
		for (key, val) in self.items():
			if str(key) in self.stored_values:
				val.saved_value = self.stored_values[str(key)]

	saved_value = property(getSavedValue, setSavedValue)

	def __setitem__(self, key, item):
		dict.__setitem__(self, key, item)
		if str(key) in self.stored_values:
			item.saved_value = self.stored_values[str(key)]
			item.load()

	def dict(self):
		return self

# Like the classes above, just with a more "native"
# syntax.
#
# some evil stuff must be done to allow instant
# loading of added elements. this is why this class
# is so complex.
#
# we need the 'content' because we overwrite
# __setattr__.
# If you don't understand this, try adding
# __setattr__ to a usual exisiting class and you will.
class ConfigSubsection(object):
	def __init__(self):
		self.__dict__["content"] = ConfigSubsectionContent()
		self.content.items = { }
		self.content.stored_values = { }

	def __setattr__(self, name, value):
		if name == "saved_value":
			return self.setSavedValue(value)
		assert isinstance(value, (ConfigSubsection, ConfigElement, ConfigSubList, ConfigSubDict)), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
		content = self.content
		content.items[name] = value
		x = content.stored_values.get(name, None)
		if x is not None:
			#print "ok, now we have a new item,", name, "and have the following value for it:", x
			value.saved_value = x
			value.load()

	def __getattr__(self, name):
		if name not in self.content.items:
			raise AttributeError(name)
		return self.content.items[name]

	def getSavedValue(self):
		res = self.content.stored_values
		for (key, val) in self.content.items.items():
			sv = val.saved_value
			if sv is not None:
				res[key] = sv
			elif key in res:
				del res[key]
		return res

	def setSavedValue(self, values, append = False):
		values = dict(values)
		if append:
			try:
				self.content.stored_values.update(values)
			except:
				self.content.stored_values = values
		else:
			self.content.stored_values = values
		for (key, val) in self.content.items.items():
			value = values.get(key, None)
			if value is not None:
				if append and isinstance(val, ConfigSubsection):
					val.setSavedValue(value, append)
				else:
					val.saved_value = value

	saved_value = property(getSavedValue, setSavedValue)

	def save(self):
		for x in self.content.items.values():
			x.save()

	def load(self):
		for x in self.content.items.values():
			x.load()

	def dict(self):
		return self.content.items

# the root config object, which also can "pickle" (=serialize)
# down the whole config tree.
#
# we try to keep non-existing config entries, to apply them whenever
# a new config entry is added to a subsection
# also, non-existing config entries will be saved, so they won't be
# lost when a config entry disappears.
class Config(ConfigSubsection):
	def __init__(self):
		ConfigSubsection.__init__(self)

	def pickle_this(self, prefix, topickle, result):
		for (key, val) in topickle.items():
			name = '.'.join((prefix, key))
			if isinstance(val, dict):
				self.pickle_this(name, val, result)
			elif isinstance(val, tuple):
				result += [name, '=', val[0], '\n']
			else:
				result += [name, '=', val, '\n']

	def pickle(self):
		result = []
		self.pickle_this("config", self.saved_value, result)
		return ''.join(result)

	def unpickle(self, lines, base_file=True, append = False):
		tree = { }
		for l in lines:
			if not l or l[0] == '#':
				continue

			n = l.find('=')
			name = l[:n]
			val = l[n+1:].strip()

			names = name.split('.')
#			if val.find(' ') != -1:
#				val = val[:val.find(' ')]

			base = tree

			for n in names[:-1]:
				base = base.setdefault(n, {})

			base[names[-1]] = val

			if not base_file: # not the initial config file..
				#update config.x.y.value when exist
				try:
					configEntry = eval(name)
					if configEntry is not None:
						configEntry.value = val
				except (SyntaxError, AttributeError):
					pass

		# we inherit from ConfigSubsection, so ...
		#object.__setattr__(self, "saved_value", tree["config"])
		if "config" in tree:
			self.setSavedValue(tree["config"], append)

	def saveToFile(self, filename):
		saveFile(filename, self.pickle())

	def loadFromFile(self, filename, base_file=False, append = False):
		f = open(filename, "r")
		lines_read = f.readlines()
		lines = []

		# HACK to migrate changed unicable configuration
		for l in lines_read:
			changed = False
			tmp = l.split('=')
			x = tmp[0].split('.')
			ent = len(x)
			if ent > 6:
				if x[1] == 'Nims' and x[3] == 'advanced' and x[6].startswith('unicable'):
					if ent > 8 and x[8] in ('vco', 'scr', 'product'):
						if x[8] != 'product':
							del x[9]
						del x[7]
						changed = True
					elif x[6] == 'unicableLnbManufacturer':
						x[6] = 'unicableLnb.manufacturer'
						changed = True
					elif x[6] == 'unicableMatrixManufacturer':
						x[6] = 'unicableMatrix.manufacturer'
						changed = True
					if changed:
						tmp[0] = '.'.join(x) 
						l = '='.join(tmp)
						print("UNICABLE MIGRATION", l, end=' ')
			lines.append(l)

		self.unpickle(lines, base_file, append)
		f.close()

config = Config()
config.misc = ConfigSubsection()

class ConfigFile:
	CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")

	def load(self):
		try:
			config.loadFromFile(self.CONFIG_FILE, True)
		except IOError as e:
			print("unable to load config (%s), assuming defaults..." % str(e))

	def save(self):
		config.saveToFile(self.CONFIG_FILE)

	def __resolveValue(self, pickles, cmap):
		key = pickles[0]
		if key in cmap:
			if len(pickles) > 1:
				return self.__resolveValue(pickles[1:], cmap[key].dict())
			else:
				return str(cmap[key].value)
		return None

	def getResolvedKey(self, key):
		names = key.split('.')
		if len(names) > 1:
			if names[0] == "config":
				ret=self.__resolveValue(names[1:], config.content.items)
				if ret and len(ret):
					return ret
		return None

def NoSave(element):
	element.disableSave()
	return element

configfile = ConfigFile()
configfile.load()

def getConfigListEntry(*args):
	assert len(args) > 0, "getConfigListEntry needs a minimum of one argument (descr)"
	return args

def updateConfigElement(element, newelement):
	newelement.value = element.value
	return newelement

#def _(x):
#	return x
#
#config.bla = ConfigSubsection()
#config.bla.test = ConfigYesNo()
#config.nim = ConfigSubList()
#config.nim.append(ConfigSubsection())
#config.nim[0].bla = ConfigYesNo()
#config.nim.append(ConfigSubsection())
#config.nim[1].bla = ConfigYesNo()
#config.nim[1].blub = ConfigYesNo()
#config.arg = ConfigSubDict()
#config.arg["Hello"] = ConfigYesNo()
#
#config.arg["Hello"].handleKey(KEY_RIGHT)
#config.arg["Hello"].handleKey(KEY_RIGHT)
#
##config.saved_value
#
##configfile.save()
#config.save()
#print config.pickle()
