#!/usr/bin/python
#=====================================================================================
# Get data from an html form
# Validate the data, error message on a separate page
# Store in a database
#=====================================================================================
import pymysql as mydb                #Mysql 3x database driver
import HTTPparam

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

firstname  = HTTPparam.getValue('firstname')  or ""      #text field             
lastname   = HTTPparam.getValue('lastname')   or "" 
address    = HTTPparam.getValue('address')    or ""      #textarea
flavor     = HTTPparam.getValue('flavor')     or ""      #could be a list
topping1   = HTTPparam.getValue('topping1')   or ""      #checkboxes
topping2   = HTTPparam.getValue('topping2')   or "" 
topping3   = HTTPparam.getValue('topping3')   or "" 
topping4   = HTTPparam.getValue('topping4')   or "" 
creditCard = HTTPparam.getValue('creditCard') or ""      #radio button

msg = ""

"""===================================================================================
 function validate():
      validates the content of the html form input fields (all fields are required)    
==================================================================================="""
def validate():                                     #function validate
        
    global msg

    if firstname == "" :
        print("<font color=red>Please enter First Name</font>")
        msg = 'error'
        return 
    if lastname == "" :
        print("<font color=red>Please enter Last Name</font>")
        msg = 'error'
        return 
    if address == "" :
        print("<font color=red>Please enter your Address</font>")
        msg = 'error'
        return 
    if flavor == "" :
        print("<font color=red>Please choose ice cream flavor(s)</font>")
        msg = 'error'
        return 
    if (topping1+topping2+topping3+topping4) == "" :
        print("<font color=red>Please select topping(s)</font>")
        msg = 'error'
        return 
    if creditCard == "" :
        print("<font color=red>Please select Credit Card</font>")
        msg = 'error'
        return 
        
"""===================================================================================
 function saveDB():
          save data to Database    
==================================================================================="""
def saveDB():                                       #save to database
            
    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

    params = {
        'host'    :'localhost',               #the local host
        'port'    : 3306,                     #MySql port number
        'user'    :'demo2',                   #the userid
        'password':'demo2',                   #the password    
        'database':'demo2'                    #the name of the mysql database
    }

    sql  = F"""INSERT INTO cust_order   
               VALUES(0,'{firstname}','{lastname}','{address}','{flavors}','{toppings}','{creditCard}',1)"""    
               
#   print(sql)                                  #debugging to ensure SQL code is OK

    try:    
        conn  = mydb.connect(host='localhost',user='demo2',password='demo2',database='demo2')   #connect to db
#(or)   conn  = mydb.connect(**params)          #connect to database (**params unpacks the array)

        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
        print(msg)
        return     
                              
    print("<font color=red>Your order has been saved successfully</font>")
     
    cursor.close()                           #close the cursor/buffer
    conn.close()                             #close the connection

"""===================================================================================
   Main code
==================================================================================="""
validate()                     #call validate
if msg=='' : saveDB()          #if no errors, save in database
"""================================================================================"""


#=== 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
#================================================================================