#!/usr/bin/env python3
#=====================================================================================
# Call webStock.py?symbol=name  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/webStock.py" 

webParam = cgi.FieldStorage()                           #obtain the http for elements

if (len(sys.argv)) > 1:                                 #if argument provided
    symbol = sys.argv[1]                                #take it
else:
    symbol = webParam.getvalue('symbol') or 'AAPL'      #obtain http parameter, if none, use AAPL 
    
##################################################################################
#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=

url2 = url + '?' + 'symbol=' + symbol               #establish the url?symbol=xyz

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

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

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

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 ('    {:10s} {:s} {:s}'.format(key, '==>', header[key] ))

print("DATA INFO...")
for entry in data:
    for key in entry: 
        print ('    {:10s} {:s} {:s}'.format(key, '==>', entry[key] ))
        
print('</pre>')
print('</body>')
print('</html>')