#!/usr/bin/python
#=====================================================================================
# Get data from a database
# Display to an html form
# Allow filtering/searching through the data
# Allow sorting 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_field, sort_seq, filter

    filter     = HTTPparam.getValue('search') or ""   
    sort_field = HTTPparam.getValue('sort')   or "lastname"
    sort_seq   = HTTPparam.getValue('seq')    or "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 " \
             + "FROM cust_order "                                                      \
             + "WHERE firstname  like '%" + filter + "%' "                             \
             + "   OR lastname   like '%" + filter + "%' "                             \
             + "   OR address    like '%" + filter + "%' "                             \
             + "   OR flavor     like '%" + filter + "%' "                             \
             + "   OR topping    like '%" + filter + "%' "                             \
             + "   OR creditCard like '%" + filter + "%' "                             \
             + "ORDER BY lower(" + sort_field + ") " + sort_seq                
        
#       print(sql)                                            #debugging
         
        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      

    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_field, sort_seq, filter
    
    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>
        <form action=getFromDBsrch.cgi method=GET>
        Search for: <input type=text name=search value=
    """, end='')
    print("'" + filter + "'", end='')
    print("""
        '> 
        <input type=submit value=search> 
        </form>
        <table bgcolor=lightyellow border=1>
        <tr bgcolor=tan>
    """)                           
        
    print("<th> Order # </a>")
    print("<th><a href=getFromDBsrch.cgi?sort=lastname&seq="  +sort_seq+"&search="+filter+"> Name       </a>")
    print("<th><a href=getFromDBsrch.cgi?sort=address&seq="   +sort_seq+"&search="+filter+"> Address    </a>")
    print("<th><a href=getFromDBsrch.cgi?sort=flavor&seq="    +sort_seq+"&search="+filter+"> Flavors    </a>")
    print("<th><a href=getFromDBsrch.cgi?sort=topping&seq="   +sort_seq+"&search="+filter+"> Toppings   </a>")
    print("<th><a href=getFromDBsrch.cgi?sort=creditCard&seq="+sort_seq+"&search="+filter+"> 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 \n 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
#================================================================================