
# Invivo AI challenge simulation environment
# Copyright 2009 Simon Funk, Alejandro Dubrovsky
#
# 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 3 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

def importObject(moduleName, defaultName):
	"""Imports a single named object from a module.

	If moduleName is of the form "module.var" then this
	imports var from module.  ("module.submodule.submodule.[...].var
	is also supported.)

	If moduleName is of the form "module" then this
	imports defaultName from module.
	"""
	parts = moduleName.split(".")

	if len(parts) == 1:
		moduleName = parts[0]
		varname    = defaultName
	else:
		moduleName = '.'.join(parts[0:-1])
		varname    = parts[-1]

	module = __import__(moduleName, fromlist=[varname])
	return getattr(module, varname)


class ObjectWithProperties(object):

	"""Constructors for subclasses of this class can take a list of properties as
	a dictionary (or keyword parameters if the subclass chooses) which will override
	any class variables by the same name.  Properties are checked against
	existing class (or instance, if pre-initted by the subclass) variables
	to make sure they are overriding existing (and hence expected) variables.

	Basically this just saves you having to manually copy from the __init__ parameters
	to the self.xyz instance variables when the two have the same name.
	"""

	def __init__(self, properties={}):
		"""Properties is a dict of key/value pairs.
		See defaults in each subclass for available properties.
		"""
		#
		# Override defaults with passed list:
		#
		for key, val in properties.items():
			if not hasattr(self, key):
				raise Exception("Unknown property: %s"%(key,))
			setattr(self, key, val)

	@classmethod
	def splitProps(cls, properties):
		"""This util takes a dict of properties and returns
		two dicts (2-tuple) where the first is all properties
		which are valid (keys) to pass to __init__ for this class,
		and the second is everything else.
		"""
		a = {}
		b = {}
		for key, val in properties.items():
			if hasattr(cls, key):
				a[key] = val
			else:
				b[key] = val
		return a, b

