################################################################################
# Call a Web Service
# Prompt the user for a student lastname, generate appropriate SQL select 
# Call a web service using the SQL, and get response (JSON format)
# Encapsulate the response in HTML table, and display 
################################################################################
import urllib.request, urllib.parse         #to perform http request
import json                                 #for JSON to list of dict conversion
import webbrowser                           

#== Generate the SQL select ====================================================

lastname = input('Enter student last name, % for all: ')
lastname = lastname.lower()

sql  = "SELECT student_id, lname, fname, class.course_id, description, price  "
sql += "FROM   student  "
sql += "JOIN   class  ON student.ssn     = class.stu_ssn     "
sql += "JOIN   course ON class.course_id = course.course_id  "
sql += F"WHERE lower(lname)  LIKE  '{lastname}%'  "			
sql += "ORDER  BY 1 "

#print(sql)                                     #for debugging 

sql= urllib.parse.quote(sql)                    #perform url encoding


#== Call the Web Service =======================================================

url      = 'https://workshop.sps.nyu.edu/~sultans/util/rest/REST.php'
param    = 'user=demo&pswd=demo&db=demo&dbtype=sqlite&format=json&sql='
full_url = url +'?'+ param + sql

#print(full_url)                                #for debugging

response = urllib.request.urlopen(full_url)     #call the web service 

status  = response.status                       #should be 200 
reason  = response.reason                       #should be OK
headers = response.info()                       #a dictionary of response headers                

content = response.read()                       #read the returned data
#content = content.decode( )                    #convert bytes into string

#print(content)                                 #for debugging - to see the returned JSON


#== Convert returned JSON into List of Dictionaries ============================

list = json.loads(content)                      #convert JSON into a list of dictionaries

#print(list)                                    #for debugging


#== Display list of dictionaries in HTML table =================================

output  = "<html> \n"
output += "<h2>Result of your Query</h2> \n"

output += "<table border='2'> \n"               #create an HTML table
output += "<tr bgcolor=cyan > \n"

if not list:                                    #if nothing is returned 
    list = [ {'result' : 'No data returned'} ] 

first_row = list[0]                             #get first row
colnames  = first_row.keys()                    #get the column names

for colname in colnames :
    output += F"<th> {colname} </th>"           #print each column name
output += "</tr> \n"

for  dict  in  list :                           #for dict in list
    output += "<tr>"								
    for (name,value) in dict.items() :
        output += F"<td> {value} </td>"         #print each column value
    output += "</tr> \n"

output += "</table><br> \n"
output += "</html> \n"

#print(output)                                  #for debugging 


#== Write HTML to file, and launch a browser ===================================

htmlfile = "C:/users/samsu/desktop/output.html"	
file = open(htmlfile, 'w')                      #open the file for write
file.write(output)                              #write the file
file.close( )

webbrowser.open_new(htmlfile)                   #launch a browser