#############################################
# Converts a Request object to a Python FieldStorage


def winFieldStorage(Request):
    from StringIO import StringIO
    from cgi import FieldStorage
    # get the relevant enviroment variables from the IIS
    ServerVariables = coll2Dict(Request.ServerVariables)
    # get the content from the Request as binary
    binaryContent, size = Request.BinaryRead(int(ServerVariables['CONTENT_LENGTH']))
    # tempfile in memory
    fp = StringIO(str(binaryContent))
    fs = FieldStorage(fp=fp, environ=ServerVariables)
    fp.close()
    return fs


#############################################
# Converts a Request object to a Python dict

def _addDicts(*args):
    """
    Add dicts without overwriting values, unlike 'update()'
    if there are more than one value pr. key it creates list and appends
    """
    rs = {}
    for dict in args:
        for key, val in dict.items():
            if rs.has_key(key):
                if type(val) != type([]):
                    val = [val]
                if type(rs[key]) != type([]):
                    rs[key] = [rs[key]]
                rs[key] += val
            else:
                rs[key] = val
    return rs


def coll2Dict(collection, keep_blank_values=0):
    """
    takes an IIS collection and returns it as a dict like:
    formDict = coll2Dict(Request.Form)
    queryDict = coll2Dict(Request.QueryString)
    cookieDict = coll2Dict(Request.Cookies)
    serverDict = coll2Dict(Request.ServerVariables)
    """
    qs = {} # result dict
    queryCount = collection.count
    if queryCount > 0:
        for i in range(1, queryCount+1):
            key  = str(collection.Key(i))
            item = collection(key)
            if item.Count == 1:
                if keep_blank_values or ((not keep_blank_values) and \
                        (str(item) != '')):
                    qs[key] = str(item)
            if item.Count > 1:
                qs[key] = []
                for j in range(1, item.Count+1):
                    if keep_blank_values or ((not keep_blank_values) and \
                            (str(item(j)) != '')):
                        qs[key].append(str(item(j)))
                if len(qs[key]) == 0:
                    del(qs[key])
    return qs


def request(Request, Cookies=0, ServerVariables=0, keep_blank_values=0):
    """
    Takes a IIS Request object and returns a dict with the same values.
    per default it will only return values of Form and QueryString.
    Cookies and ServerVariables can be included in the same dict if needed.
    set "keep_blank_values=1" if keys with empty ('') values should be in the
    resulting dictionary.
    """
    query = coll2Dict(Request.QueryString, keep_blank_values)
    form  = coll2Dict(Request.Form, keep_blank_values)
    if Cookies:
        cooks = coll2Dict(Request.Cookies, keep_blank_values)
    else:
        cooks = {}
    if ServerVariables:
        serverVars = coll2Dict(Request.ServerVariables, keep_blank_values)
    else:
        serverVars = {}
    return _addDicts(query, form, cooks, serverVars)