#!/usr/bin/env python3
#=====================================================================================
# Get data from an html form
# Validate the data
# Store in a database
#=====================================================================================
import HTTPparam                        #to obtain HTTP parameters
import pymysql as mydb                  #Mysql 3x database driver
import re                               #regular expressions

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

fn_error,   ln_error,   addr_error          = '','',''
brnd_error, flav_error, top_error, cc_error = '','','',''
msg = '' 

params = HTTPparam.getAll()                         #obtain the http parameters

firstname  = params.get('firstname')  or ""         #text field             
lastname   = params.get('lastname')   or "" 
address    = params.get('address')    or ""         #textarea
brand      = params.get('brand')      or "" 
flavor     = params.get('flavor')     or ""         #could be a list
topping1   = params.get('topping1')   or ""         #checkboxes
topping2   = params.get('topping2')   or "" 
topping3   = params.get('topping3')   or "" 
topping4   = params.get('topping4')   or "" 
creditCard = params.get('creditCard') or ""         #radio button
    
        
"""===================================================================================
 function validate():
      validates the content of the html form input fields (all fields are required)    
==================================================================================="""
def validate():                                     #function validate

    global fn_error,ln_error,addr_error,brnd_error,flav_error,top_error,cc_error
    global msg
        
    if firstname=='' : fn_error   = '*'             
    if lastname==''  : ln_error   = '*'
    if address==''   : addr_error = '*'
    if brand==''     : brnd_error = '*'
    if flavor==''    : flav_error = '*'
    if topping1==''  and topping2=='' and topping3=='' and topping4=='' : top_error = '*'
    if creditCard=='': cc_error  = '*'
        
    if fn_error or ln_error or addr_error or brnd_error or flav_error or top_error or cc_error:
        msg = 'Please correct error fields above' 

"""===================================================================================
 function display():
          display the web form   
==================================================================================="""
def display(): 

    global fn_error,ln_error,addr_error,brnd_error,flav_error,top_error,cc_error
    global msg

    print(F'''
        <!DOCTYPE html>
        <html>
        <head>
        <title>Full HTML entry from</title>
        <style>                                                                 /* double {{ will print a single one */
            fieldset {{width:580px; height:320px; border-color:gold; border-radius:10px;}} 
            table    {{width:570px; background-color:lightgray; border:1px solid black; border-radius:10px;}}       
            input, textarea, select  {{ border-radius:5px}}
            select   {{width:180px}}                                      
            span     {{color:red}}
         </style>
        </head>
        <body bgcolor="lightyellow">
        <h1><center>The Ice Cream Shop</center></h1>
        <h3>Response is on the same page</h3>
        <form name="form1" method="POST" action=formToDB.cgi>             <!--the name of the current Python script-->
        <fieldset>
        <legend>Enter Fields Below</legend>    
        <table>
            <tr><td><b>Enter First Name <span> {fn_error} </span>
                <td><input type="text" name="firstname" value="{firstname}">
            <tr><tr><td><b>Last Name <span> {ln_error} </span>
                <td><input type="text" name="lastname" value="{lastname}">
            <tr><td><b>Enter Address <span> {addr_error} </span>
                <td><textarea name="address" rows="4" cols="45">{address}</textarea>
    ''')     
    print('<tr><td><b>Choose a Brand <span>' + brnd_error + '</span>')  #select list (single)
    print('<td><select name="brand">')                                  
    print('<option value="">---choose from below---</option>')
    print('<option value="BR"',end='')
    if brand =='BR': print('selected',end='')
    print('>Baskin-Robbins </option>')
    print('<option value="BJ"',end='')
    if brand =='BJ': print('selected',end='')
    print(">Ben & Jerry's</option>")
    print('<option value="C"',end='')
    if brand =='C': print('selected',end='')
    print('>Carvel</option>')
    print('<option value="CS"',end='')
    if brand =='CS': print('selected',end='')
    print('>Cold Stone</option>')
    print('<option value="HD"',end='')
    if brand =='HD': print('selected',end='')
    print('>Haagen-Dazs</option>')
    print('<option value="H"',end='')
    if brand =='H': print('selected',end='')
    print(">Hershey's</option>")
    print('</select>')
    
    print('<tr><td><b>Ice Cream Flavor <span>' + flav_error + '</span>')     #select list (with multiple option)
    print('<td><select name="flavor" SIZE="4" multiple>')
    print('<option value="vanilla"',end='')
    if 'vanilla' in flavor: print('selected',end='')
    print('>Vanilla</option>')
    print('<option value="chocolate"',end='')
    if 'chocolate' in flavor: print('selected',end='')
    print('>Chocolate</option>')
    print('<option value="strawberry"',end='')
    if 'strawberry' in flavor: print('selected',end='')
    print('>Strawberry</option>')
    print('<option value="butter-pecan"',end='')
    if 'butter-pecan' in flavor: print('selected',end='')
    print('>Butter Pecan</option>')
    print('<option value="rocky-road"',end='')
    if 'rocky-road' in flavor: print('selected',end='')
    print('>Rocky Road</option>')
    print('<option value="french-vanilla"',end='')
    if 'french-vanilla' in flavor: print('selected',end='')
    print('>French Vanilla</option>')
    print('<option value="pistachio"',end='')
    if 'pistachio' in flavor: print('selected',end='')
    print('>Pistachio</option>')
    print('</select>')
    
    print('<tr><td><b>Select Topping <span>' + top_error + '</span><td>')    #checkbox
    print('<input type="checkbox" name="topping1" value="hotFudge"',end='') 
    if topping1 !='': print('checked',end='')
    print('> Hot Fudge')
    print('<input type="checkbox" name="topping2" value="sprinkles"',end='')
    if topping2 !='': print('checked',end='')
    print('> Sprinkles')
    print('<input type="checkbox" name="topping3" value="nuts"',end='')
    if topping3 !='': print('checked',end='')
    print('> Nuts')
    print('<input type="checkbox" name="topping4" value="whippedCream"',end='')
    if topping4 !='': print('checked',end='')
    print('> Whipped Cream')
    
    print('<tr><td><b>Credit Card <span>' + cc_error + '</span><td>')        #radio button
    print('<input type="radio" name="creditCard" value="MC"',end='')
    if creditCard =='MC': print('checked',end='')
    print('>   Master Card')
    print('<input type="radio" name="creditCard" value="VISA"',end='') 
    if creditCard =='VISA': print('checked',end='')
    print('> Visa')
    print('<input type="radio" name="creditCard" value="AMEX"',end='') 
    if creditCard =='AMEX': print('checked',end='')
    print('> American Express')
    print('<input type="radio" name="creditCard" value="DISC"',end='') 
    if creditCard =='DISC': print('checked',end='')
    print('> Discover')
    
    print('''
        <tr>
        <td width=140px>
        <tr>
        <td colspan=2>
        <input type="submit" value="  Place Order  "  >
        <input type="reset"  value="Cancel"           >
        </table>
    ''')
    
    print("<p style='color:red'>" + msg + '</p>')    
    print("</fieldset>")
    print("</form>")
    print("</body>")
    print("</html>")

"""===================================================================================
 function saveDB():
          save data to Database    
==================================================================================="""
def saveDB():                                       #save to database
        
    global msg

    if firstname == '': return
    
    flavors = flavor
    if type(flavor) is list:
        flavors = ','.join(flavor)                  #join an array using commas 

    toppings = ''
    if topping1 : toppings += topping1 +','         #join all the values for toppings 
    if topping2 : toppings += topping2 +','
    if topping3 : toppings += topping3 +','
    if topping4 : toppings += topping4 +','
    toppings = re.sub(r",$", "", toppings)          #strip off the last comma for the array 

    sql  = "INSERT INTO cust_order " 
    sql += "VALUES("+ str(0) +",'"+ firstname +"','"+ lastname +"','"+ address    +"'"
    sql +=                    ",'"+ flavors   +"','"+ toppings +"','"+ creditCard +"'," + str(1) +")"

    try:    
        conn  = mydb.connect(host='localhost',user='demo2',password='demo2',database='demo2')   #connect to host

        cursor = conn.cursor()                  #create a cursor

        cursor.execute(sql);                    #execute the sql

        conn.commit()

    except mydb.Error as e:
        (errorNum, errorMsg) = e.args
        msg = 'Database Error - ' + str(errorNum) +' '+ errorMsg
        return     
                              
    msg = "Your order has been saved successfully";    
     
    cursor.close()                           #close the cursor/buffer
    conn.close()                             #close the connection

"""===================================================================================
   Main code
==================================================================================="""
if params   : validate()                    #if something was entered call validate
if msg == '': saveDB()                      #if no errors, save in database
display()                                   #validate form fields                                           
"""================================================================================"""



#=== link to see the python code ================================================
import os
import 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
#================================================================================