#!/usr/bin/env python
#=====================================================================================
# Get data from an html form
# Validate the data
# Store in a file
#=====================================================================================
import cgi                            #cgi 
import cgitb                          #cgi with traceback error handling
import re                             #regular expressions

cgitb.enable()

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

elements   = cgi.FieldStorage()                     #obtain the http parameters

firstname  = elements.getvalue('firstname')  or ""      #text field             
lastname   = elements.getvalue('lastname')   or "" 
address    = elements.getvalue('address')    or ""      #textarea
brand      = elements.getvalue('brand')      or ""      #select list (single) 
flavor     = elements.getvalue('flavor')     or ""      #select list (with multiple)
topping1   = elements.getvalue('topping1')   or ""      #checkboxes
topping2   = elements.getvalue('topping2')   or "" 
topping3   = elements.getvalue('topping3')   or "" 
topping4   = elements.getvalue('topping4')   or "" 
creditCard = elements.getvalue('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 type(flavor) is list :                               #if it is a list
        flavor2 = ','.join(flavor)                          #join it into a string , separated          

    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('''
        <!DOCTYPE html>
        <html>
        <head>
            <title>Full HTML entry from</title>
            <style>
                span   {color:red}
                select {width:160px}
            </style>
        </head>
        <body bgcolor="lightyellow">
        <h1><center>The Ice Cream Shop</center></h1>
        <form name="form1" method="POST" action="formToFile_web.py">
        <fieldset style='width:580px; height:315px; border-color:gold'>
        <legend>Enter Fields Below</legend>    
        <table bgcolor=lightgray width=570px>
    ''')
    
    print('<tr><td width=150><b>Enter First Name <span>' + fn_error    + '</span>')
    print('<td><input type="text" name="firstname" value="'  + firstname + '">')
    print('<tr><tr><td><b>Last Name <span>'    + ln_error    + '</span>')
    print('<td><input type="text" name="lastname" value="'   + lastname + '">')
    print('<tr><td><b>Enter Address <span>'    + addr_error  + '</span>')
    print('<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='')                                             #trailiong comma -> no newline
    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 colspan=2>
        <input type="submit" value="  Place Order  "  >
        <input type="reset"  value="Cancel"           >
        </table>
    ''')
    
    print("<p style='color:red'>" + msg + '</p>')
    
    print('''
        </fieldset>
        </form>
        </body>
        </html>
    ''')

"""===================================================================================
 function saveFile():
          save data to a file   
==================================================================================="""
def saveFile():                                       #save to database
        
    global msg

    if firstname == '': return

    file = '/home/ssultans/data/cust_order.file'    #server file
    
    addr = address.replace('\n','__')               #replace newline with __

    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 


    output = open(file,'a')                         #open the file for append
    
    rec = firstname+'||'+lastname+'||'+addr+'||'+flavors+'||'+toppings+'||'+creditCard
    
    x = output.write(rec + "\n")
    
    output.close  
                              
    msg = "Your order has been saved successfully " + str(x);    
     
"""===================================================================================
   Main code
==================================================================================="""
if elements:  validate()                     #if something was entered call validate
if msg == '': saveFile()                     #if no errors, save to a file
display()                                    #validate form fields                                           
"""================================================================================"""


#=== link to see the python code =================================================
import os, sys
sys.path.insert(0,'/home/sultans/web/python/demo')
import zCode                          #import func to display the Python code
filename = os.path.abspath(__file__)  #get absolute file name 
zCode.display(filename)               #call it
#=================================================================================