# vim: set fileencoding=utf-8 :
import os, urllib, common

def querystring(document):
    startkey=os.environ.get('PAGE_STARTKEY');
    startkey_docid=os.environ.get('PAGE_STARTKEY_DOCID');
    map={};
    encode={ 'key': True, 'keys': True, 'startkey': True, 'endkey': True };
    limit="limit";
    for k in iter(document.keys()):
        value=document[k];
        if k == limit:
            value+=1
        try:
            if encode[k]:
                value=common.compact(value);
        except:
            pass;
        # lowercase booleans for consistency
        # cannot use == must use *is* so that
        # integers are not coerced
        if value is True:
            value=str(True).lower();
        if value is False:
            value=str(False).lower();
        map[k]=value
    # pagination keys should already be JSON encoded
    if startkey:
        map['startkey']=startkey;
    if startkey_docid:
        map['startkey_docid']=startkey_docid;
    return urllib.urlencode(map)
