from MoinMoin.web.serving import make_application
## import the ISAPI WSGI glue
import isapi_wsgi
import sys
from sys import exc_info
from traceback import format_tb

class ExceptionMiddleware(object):
	"""The middleware we use."""

	def __init__(self, app):
		self.app = app

	def __call__(self, environ, start_response):
		"""Call the application can catch exceptions."""
		appiter = None
		# just call the application and send the output back
		# unchanged but catch exceptions
		try:
			appiter = self.app(environ, start_response)
			for item in appiter:
				yield item
		# if an exception occours we get the exception information
		# and prepare a traceback we can render
		except:
			e_type, e_value, tb = exc_info()
			traceback = ['Traceback (most recent call last):']
			traceback += format_tb(tb)
			traceback.append('%s: %s' % (e_type.__name__, e_value))
			# we might have not a stated response by now. try
			# to start one with the status code 500 or ignore an
			# raised exception if the application already started one.
			try:
				start_response('500 INTERNAL SERVER ERROR', [('Content-Type', 'text/plain')])
			except:
				pass
			yield '\n'.join(traceback)

   # wsgi applications might have a close function. If it exists
   # it *must* be called.
		if hasattr(appiter, 'close'):
			appiter.close()

# The entry points for the ISAPI extension.

def __ExtensionFactory__():
	#add path to sys.paht where wikiconfig.py can be found
	sys.path.insert(0, 'c:/moin')
	## new way to instantiate in 1.9
	moinmoinApp = make_application(shared=True)
	errorHandledApp=ExceptionMiddleware(moinmoinApp)
	return isapi_wsgi.ISAPIThreadPoolHandler(errorHandledApp)

## Installation code
if __name__=='__main__':
	from isapi.install import *

	# If run from the command-line, install ourselves.
	params = ISAPIParameters()

	sm = [ScriptMapParams(Extension="*", Flags=0)]

	# Create a Virtual Directory per wiki
	params.VirtualDirs = [	VirtualDirParameters(
		#Server="mshost",
		Name="wiki",
		Description = "ISAPI-WSGI gateway for testwiki" ,
		ScriptMaps = sm,
		ScriptMapUpdate = "replace" )
	]

	HandleCommandLine(params)
