#!/usr/bin/env python3
#=====================================================================================
# Call webService.py?studentId=99&format=JSON|XML  web service
# input can come from 1) command line argument, or 2) from url?studentId=999
# print result
#=====================================================================================
import sys              #import sys for command line arguments
import cgi              #import cgi 
import urllib.request   #urllib.request module allows fetching of urls 
import json             #to convert a json string to a Python dict/array
import cgitb            #import cgi traceback for error handling
cgitb.enable()

print("Content-Type: text/html \n")                     #required cgi header

url = "https://workshop.sps.nyu.edu/~sultans/python/demo/ws/webService.py" 

webParam = cgi.FieldStorage()                           #obtain the http parameters
stud_id = webParam.getvalue('studentId') or '1'         #obtain studentId parameter, if none, use 1 
format  = webParam.getvalue('format')    or 'JSON'      #obtain format    parameter, if none, use JSON 

if (len(sys.argv)) > 1:                                 #if batch argument provided
    stud_id = sys.argv[1]                               #obtain the student_id
if (len(sys.argv)) > 2:                                 #if 2nd batch argument provided
    format = sys.argv[2]                                #obtain the format

##################################################################################
#encode64: encode user:pswd to base64
##################################################################################
def encode64(input):
    import base64                                   #encode base64

    input = input.replace('Basic','')               #remove 'Basic'
    input = input.strip()                           #trim whitespace
    bArray      = input.encode()                    #convert the string to byte array
    encoded_arr = base64.b64encode(bArray)          #encode it base64
    encoded_str = encoded_arr.decode()              #convert the byte array back to string
    encoded_str = 'Basic ' + encoded_str            #re-add 'Basic'
    return(encoded_str)
##################################################################################
    
authValue    = 'Basic student:123'
encryptValue = encode64(authValue)                    # Basic c3R1ZGVudDoxMjM=

param = 'studentId=' + stud_id + '&format=' + format
url2 = url + '?' + param                              #establish the url?studentId=999&format=JSON|XML

req  = urllib.request.Request(url2)                   #create a request object
req.add_header('Authorization', encryptValue)         #add 'Authorization' value header 
resp = urllib.request.urlopen(req)                    #send the request

data = resp.read()                                    #read the returned data 

print('''                                                
    <html>
    <head>
    <title>Python calling a Python Web Service</title>
    </head>
    <body>    
    <h2>Python pgm calling a Python Web Service</h2>
    <pre>
''')                                                     

##################################################################################
if format.upper() == 'JSON':
    obj = json.loads(data)                              #convert json string into dict/array

    header = obj['header']                              #get the headers as dictionary
    data   = obj['data']                                #get the data as array of dictionaries                          

    print("HEADER INFO...")
    for key in header:
        print ('    {:12s} {:s} {:s}'.format(key, '==>', header[key] ))

    print("DATA INFO...")
    for entry in data:
        for key in entry:
            value = entry[key]
            value = str(value) 
            print ('    {:12s} {:s} {:s}'.format(key, '==>', value ))
        print()
        
##################################################################################
if format.upper() == 'XML':
    print("DATA INFO...")
    str = data.decode("utf-8")                       #convert byte array to a string
    print(str)

print('</pre>')
print('</body>')
print('</html>')