from MetadataService.InterfaceServer import InterfaceServer
from DocXMLRPCServer import DocXMLRPCServer
import ConfigParser
from MetadataService.common import from_xml_params,to_xml_params
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher

class XMLRPCInterfaceServer(InterfaceServer,DocXMLRPCServer):
	""" A self-documenting implementation of the public interface server using standard TCP/HTTP transport """
	
	def __init__(self,config,interfaces):
		InterfaceServer.__init__(self,interfaces=interfaces,config=config)
		self.set_component_name("InterfaceServer.TCPXMLRPC")
		try:
			address = self.config.get("TCP interface","address")
		except (ConfigParser.NoSectionError,ConfigParser.NoOptionError):
			address = "0.0.0.0"
		try:
			port = self.config.getint("TCP interface","port")
		except (ConfigParser.NoSectionError,ConfigParser.NoOptionError):
			port = 2081

		DocXMLRPCServer.__init__(self,(address,port))
		self.set_server_title("Metadata service XML-RPC interface")
		self.set_server_name("Metadata service XML-RPC interface")
		self.set_server_title("This server maintains a list of public interfaces to the metadata service.")
		self.register_instance(self.public_interfaces)
		self.register_introspection_functions()
		self.register_multicall_functions()
		self.setDaemon(True) # fixme, this avoids the blocking upon shutdown
		
	def run(self):
		self.serve_forever()

	# FIXME: this is the place to determine user ID and submit it to the public interface
	# for that, we need to write our own request handlers
	def _dispatch(self,method,params):
		params = from_xml_params(params)
		return to_xml_params(SimpleXMLRPCDispatcher._dispatch(self,method,params))
