# Copyright (c) 2006 by Seo Sanghyeon
# Copyright (c) 2006 by Christopher Baus
# 2006-03-30 sanxiyn Created
# 2006-10-29 baus Added all WSGI environ variables.
#
"""An IronPython module which acts as a thin WSGI wrapper for ASP.NET servers.
It works inconjunction with WSGI.cs which handles ASP.NET HTTPRequests,
and converts them to WSGI events.  This module is loaded by the WSGI.cs
handler.
"""

def make_environ(request):
    """Creates an wsgi environ dictionary from ASP.NET HTTPRequest object.  This is specific
    To IronPython as the request is a .NET object.
    """
    environ = {}
# Is there a way to pass the root path into the function?
    rootpath = "/service"
    environ['wsgi.version'] = (1, 0)
    environ['wsgi.input'] = file(request.InputStream)
    environ['wsgi.url_scheme'] = request.Url.Scheme
    environ['REQUEST_METHOD'] = request.HttpMethod
    environ['SCRIPT_NAME'] = ''
    environ['PATH_INFO'] = request.Path[request.Path.index(rootpath) + len(rootpath):]
    environ['QUERY_STRING'] = str(request.Url.Query)[1:]
    environ['CONTENT_TYPE'] = request.ContentType
    environ['CONTENT_LENGTH'] = str(request.ContentLength)
    environ['SERVER_NAME'] = request.Url.Host
    environ['SERVER_PORT'] = str(request.Url.Port)
# There isn't an obvious way to get request protocol from the     
#    environ['SERVER_PROTOCOL'] = 
    return environ

def make_start_response(response):
    def start_response(status, response_headers):
        response.Status = status
        for header_name, header_value in response_headers:
            response.AddHeader(header_name, header_value)
    return start_response

def run_application(context, application):
    request = context.Request
    response = context.Response
    environ = make_environ(request)
    start_response = make_start_response(response)
    response.BufferOutput = False;
    for data in application(environ, start_response):
        response.Write(data)
