#!/usr/bin/python
#=====================================================================================
# Get data from a database
# Display to an html form
# Allowing of data when click on column header
#=====================================================================================
import pymysql as mydb                      #Mysql 3x database driver
import re                                   #regular expressions
import HTTPparam
  
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():
 
    global sort_seq

    sort_field = HTTPparam.getValue('sort')
    sort_seq   = HTTPparam.getValue('seq')
    if not sort_field: sort_field = 'lastname'            
    if not sort_seq  : sort_seq   = 'asc'            

    host   = 'localhost'               #the local host
    port   =  3306                     #MySql port number
    userid = 'demo2'                   #the userid
    pswd   = 'demo2'                   #the password    
    db     = 'demo2'                   #the name of the mysql database
 
    try:
        conn = mydb.connect(host=host,user=userid,password=pswd,database=db)     #connect to host
     
        cursor = conn.cursor()                                  #create a cursor
     
        sql  = "SELECT firstname,lastname,address,flavor,topping,creditCard,order_id " 
        sql += "FROM cust_order " 
        sql += "ORDER BY lower("+sort_field+")" + sort_seq      #not case sensitive
     
        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
        return      

    """                                      #comment
    results = cursor.fetchall()              #get all the rows
    for row in results:
        print(row)
    """
     
    """                                      #comment
    row = cursor.fetchone()                  #get one row at a time
    while row is not None:
        lastname   = row[0]
        firstname  = 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)+'<br>') 
    """
#   numCols = len(cursor.description)

    i=0
    row = cursor.fetchone()                         #get first row 
    while row is not None:
        data.append(row)
        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():

    global sort_seq
    
    if sort_seq == 'asc': 
        sort_seq = 'desc'                   #flip the sort seq
    else:
        sort_seq = 'asc'

    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 # </a>")
    print("<th><a href=getFromDBsort.cgi?sort=lastname&seq="  +sort_seq+"> Name       </a>")
    print("<th><a href=getFromDBsort.cgi?sort=address&seq="   +sort_seq+"> Address    </a>")
    print("<th><a href=getFromDBsort.cgi?sort=flavor&seq="    +sort_seq+"> Flavors    </a>")
    print("<th><a href=getFromDBsort.cgi?sort=topping&seq="   +sort_seq+"> Toppings   </a>")
    print("<th><a href=getFromDBsort.cgi?sort=creditCard&seq="+sort_seq+"> Credit Card</a>")

    for row in data:                                    #loop thru the data rows
        print("<tr>", end='')
#       for value in row:                               #loop thru columns
#           print("<td>"+ str(value) +"  </td>", 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("<td>"+ str(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
#================================================================================