#===============================================================================================
# Return HTTP GET and POST input parameters as a dictionary
# Functions:
#     getGET()       = return the GET parameters as a dictionary
#     getPOST()      = return the POST parameters as a dictionary 
#     getAll()       = return both GET and POST parameters as a single dictionary
#     getValue(name) = return the value of a single param
#===============================================================================================
import os, sys
from urllib import parse

method = os.environ.get('REQUEST_METHOD')
postParamStr = ''                           #to save POST parameters since stdin cannot be re-read

#===============================================================================================
# Return the GET parameters as a dictionary
# parse_qs will convert param string into a dictionary. All values are returned as lists
#===============================================================================================
def getGET():

    try:
        getParamStr = os.environ.get('QUERY_STRING')    #obtain GET param from query_string
    except:
        getParamStr = ''
        
#    getParamStr = '1=a&2=b1&2=b2&2=b3&2=b4&3=c&5='      #test/debug only
    if not getParamStr: return {}                       #if no GET params return empty dictionary

    getParamDict = parse.parse_qs(getParamStr)          #convert param string to dictionary
    for (key, value) in getParamDict.items():           #loop through dictionary
        if len(value) == 1:                             #if the value is only a single value
            getParamDict[key] = value[0]                #replace the list with the single value

    return(getParamDict)

#===============================================================================================
# Return the POST parameters as a dictionary
# PS. You cannot re-read stdin. As such, once it is read, it is saved in global for later use 
# parse_qs will convert param string into a dictionary. All values are returned as lists
#===============================================================================================
def getPOST():
    global postParamStr                                 #to access global postParamStr                                 

    if not postParamStr:                                #if stdin was not previous read
        try:
            req_body = sys.stdin.readlines()            #read entire HTTP request body from stdtin
            postParamStr = req_body[0]                  #access first line of input
        except:
            postParamStr = ''
 
#    postParamStr = '2=bb1&2=bb2&2=bb3&4=dd&5='          #test/debug only
    if not postParamStr: return {}                      #if no POST params return empty dictionary

    postParamDict = parse.parse_qs(postParamStr)        #convert param string to dictionary
    for (key, value) in postParamDict.items():          #loop through dictionary
        if len(value) == 1:                             #if the value is only a single value
            postParamDict[key] = value[0]               #replace the list with the single value

    return(postParamDict)

#===============================================================================================
# Return all parameters (both GET and POST) as a single merged dictionary
#===============================================================================================
def getAll():

    getParamDict  = getGET()
    postParamDict = getPOST()
       
    if not getParamDict and not postParamDict: return {}    #if no GET and no POST params return empty dictionary
        
    allParamDict = getParamDict                             #start with GET param
    
    for (key,value) in postParamDict.items():               #loop through all POST params
        if key not in allParamDict:                         #if key does not already exist in dictionary
            allParamDict[key] = value                       #add a key/value pair to dictionary
        else:                                               #if key already exists - Same field name from both GET and POST 
            if type(value) != list:                         #if value is not already a list 
                allParamDict[key] = [ allParamDict[key] ]   #  make it a list
                allParamDict[key].append(value)             #append the next value to the list
            else:                                           #if already a list
                for val in value:                           #  loop through the individual values
                    allParamDict[key].append(val)           #  append each to the list of values

    return(allParamDict)    
 
#===============================================================================================
# Return the value of a single HTTP parameter by name
#===============================================================================================
def getValue(name):
    allParams = getAll()                                    #get all parameters
    value  = allParams.get(name)                            #get value of a single parameter                               
    if (value is None): value= ''
    return(value)
#===============================================================================================
'''
get  = getGET()                  #test/debug only 
post = getPOST()
both = getAll()
two  = getValue('4')

print(get)
print(post)
print(both)
print(two)
'''