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

class SocketXMLRPCInterfaceServer(InterfaceServer,SocketXMLRPCServer):
	""" 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.SocketXMLRPC")

		try: sockaddr = self.config.get("socket interface","socket")
		except (ConfigParser.NoSectionError,ConfigParser.NoOptionError):
			sockaddr = os.path.join(self.config.get_data_dir(),"socket")
		try: os.unlink(sockaddr)
		except OSError,e:
			if e.errno == 2: pass
			else: raise
		SocketXMLRPCServer.__init__(self,sockaddr)
		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
	def _dispatch(self,method,params):
		params = from_xml_params(params)
		return to_xml_params(SimpleXMLRPCDispatcher._dispatch(self,method,params))
