#!/usr/bin/python
#=====================================================================================
# Get data from a database
# Display to an html form
#=====================================================================================
import pymysql as mydb                      #Mysql 3x database driver
import re                                    #regular expressions

data = []                                   #2 dim array

print("Content-Type: text/html \n")         #required http response header (w/ extra line)

'''===================================================================================
read_data: read data from a database
==================================================================================='''
def read_data():
      
    try:    
        conn = mydb.connect(host='localhost',db='demo2',user='demo2',password='demo2',port=3306)  #connect to db
     
        cursor = conn.cursor()                                  #create a cursor
     
        sql  = "SELECT firstname,lastname,address,flavor,topping,creditCard,order_id " 
        sql += "FROM cust_order " 
        sql += "ORDER BY order_id" 

#       print(sql)                                  #debugging to ensure SQL code is OK
     
        result = cursor.execute(sql);                           #execute the query
     
    except mydb.Error as e:
        errorNum = e.args[0]
        errorMsg = e.args[1]
        error = 'Database Error - ' + str(errorNum) + errorMsg
        print(error)
        return      

#---Option one (get all the rows)----------------------------------------
#    results = cursor.fetchall()             #get all the rows at once
#    for row in results:                     #loop thru the list of rows
#        for col in row:                     #loop thru the tuple of columns                     
#            print(col, ' ', end='') 
#        print('<br>') 
     
#---Option two  (get one row at a time)----------------------------------
#    row = cursor.fetchone()                #get one row at a time
#    while row is not None:                 #loop until no more rows   
#        firstname  = row[0]
#        lastname   = row[1]
#        address    = row[2]
#        flavor     = row[3]
#        topping    = row[4]
#        creditCard = row[5]
#        order_id   = row[6]
#        print(lastname+' '+firstname+' '+address+' '+flavor+' '+topping+' '+creditCard+' '+str(order_id) )
#        print('<br>') 
#        row = cursor.fetchone()            #get next row

    i=0
    row = cursor.fetchone()                 #get first row 
    while row is not None:                  #loop until no more rows
        data.append(row)                    #save in the data[] list
        i+=1
        row = cursor.fetchone()             #get next row
     
    cursor.close()                          #close the cursor/buffer
    conn.close()                            #close the connection

'''===================================================================================
display: display data on the html page
==================================================================================='''
def display():

    print("""
        <html>
        <head>
        <title>Retrieve data from database</title>    
        <style>
            a     {text-decoration:none; color:brown}
            table {font:10pt arial; border:solid 2px black; border-collapse:collapse; margin-left:70px; background-color:#eeeeee; } 
            th,td {border:solid 1px black; padding-left:5px; padding-right:5px; vertical-align:top;}
        </style>
        <body bgcolor=lightyellow>
        <h1><center>The Ice Cream Shop</center></h1>
        <table bgcolor=lightyellow border=1>
        <tr bgcolor=tan>
    """)                           
        
    print("<th>Order#<th>Name<th>Address<th>Flavors<th>Toppings<th>Credit Card \n")

    for row in data:                                    #loop thru the data rows
        print ("<tr>", end='')
        firstname  = row[0]
        lastname   = row[1]
        address    = row[2]
        flavor     = row[3]
        topping    = row[4]
        creditCard = row[5]
        order_id   = row[6]

        name = firstname +' '+ lastname
        addr = re.sub(r"\n", "<br>", address)           #replace _ with <br>
        flav = re.sub(r",",  "<br>", flavor)            #replace , with <br>
        top  = re.sub(r",",  "<br>", topping)           #replace , with <br>
        
        print(F"<td> {order_id} <td> {name} <td> {addr} <td> {flav} <td> {top} <td> {creditCard}" , end='')
        print("</tr>")

    print("</table>")
    print("</body>")
    print("</html>")

'''===================================================================================
main code
==================================================================================='''
read_data();
display();



#=== link to see the python code ================================================
import os, sys
sys.path.insert(0,'/home/staff/sultan/public_html/cgi-bin/python')
import zCode                          #import func to display the Python code
filename = os.path.abspath(__file__)  #get absolute file name 
zCode.display(filename)               #call it
#================================================================================