#!/usr/bin/env python3
#=====================================================================================
# A Typical html form validation and processing
#=====================================================================================
import HTTPparam                           

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

params     = HTTPparam.getAll()                 #get all 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 ""     #select list (single) 
flavor     = params.get('flavor')     or ""     #select list (with multiple)
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
 
if type(flavor) is list :                               #if it is a list
    flavor = ', '.join(flavor)                          #join it into a string , separated          

msg = ''                                                #global variable

#-------------------------------------------------------------------------------------
# Function to validate entry fields (must be defined before use)
#-------------------------------------------------------------------------------------
def validate():

    global msg                             #needed to modify global variable
                                           #no need if access to global is read only
    if firstname=='':
        msg = 'Please enter your firstname'
    elif lastname=='': 
        msg = 'Please enter your lastname'
    elif address=='': 
        msg = 'Please enter your address'
    elif brand=='': 
        msg = 'Please choose an ice cream brand'
    elif flavor=='': 
        msg = 'Please choose one or more flavors'
    elif topping1=='' and topping2=='' and topping3=='' and topping4=='': 
        msg = 'Please choose one or more toppings'
    elif creditCard=='': 
        msg = 'Please choose a credit card type'

#-------------------------------------------------------------------------------------
# Function to display the form (must be defined before use)
#-------------------------------------------------------------------------------------
def display():

    global msg                             #needed to modify global variable
                                           #no need if access to blobal is read only
    print(F'''
        <!DOCTYPE html>
        <html>
        <head>
        <title>Full HTML entry from</title>
        <style>                                                         /* double {{ will print a single one */
            fieldset {{width:580px; height:315px; 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}}                                      
        </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=form6.cgi>              <!--the name of the current Python script-->
        <fieldset>
        <legend>Enter Fields Below</legend>    
        <table>
            <tr><td><b>Enter First Name
                <td><input type="text" name="firstname" value="{firstname}">
            <tr><tr><td><b>Last Name
                <td><input type="text" name="lastname"  value="{lastname}">
            <tr><td><b>Enter Address
                <td><textarea name="address" rows="4" cols="45">{address}</textarea>
    ''')                                
    BR_selected = 'selected' if brand=='Baskin-R'  else '' 
    BJ_selected = 'selected' if brand=='BenJerry'  else ''
    CR_selected = 'selected' if brand=='Carvel'    else ''
    CS_selected = 'selected' if brand=='ColdStone' else ''
    HD_selected = 'selected' if brand=='Haagen-D'  else ''
    HS_selected = 'selected' if brand=='Hershey'   else ''
                                                                        #select list (single)
    print(F'''<tr><td><b>Choose a Brand 
              <td><select name="brand">                                  
              <option value="">---choose from below---</option> 
              <option value="Baskin-R"  {BR_selected} >Baskin-Robbins </option>
              <option value="BenJerry"  {BJ_selected} >Ben & Jerry's  </option>
              <option value="Carvel"    {CR_selected} >Carvel         </option>
              <option value="ColdStone" {CS_selected} >Cold Stone     </option>
              <option value="Haagen-D"  {HD_selected} >Haagen-Dazs    </option>
              <option value="Hershey"   {HS_selected} >Hershey's      </option>
    </select>''')

    VA_selected = 'selected' if 'Vanil'  in flavor else ''
    CH_selected = 'selected' if 'Choc'   in flavor else ''
    SW_selected = 'selected' if 'Straw'  in flavor else ''
    BP_selected = 'selected' if 'ButPec' in flavor else ''
    RR_selected = 'selected' if 'RockyR' in flavor else ''
    FV_selected = 'selected' if 'FrchV'  in flavor else ''
    PI_selected = 'selected' if 'Pista'  in flavor else ''
                                                                        #select list (multiple)
    print(F'''<tr><td><b>Ice Cream Flavor                                
              <td><select name="flavor" SIZE="4" multiple="multiple">
              <option value="Vanil"  {VA_selected} >Vanilla       </option> 
              <option value="Choc"   {CH_selected} >Chocolate     </option> 
              <option value="Straw"  {SW_selected} >Strawberry    </option> 
              <option value="ButPec" {BP_selected} >Butter Pecan  </option> 
              <option value="RockyR" {RR_selected} >Rocky Road    </option> 
              <option value="FrchV"  {FV_selected} >French Vanilla</option> 
              <option value="Pista"  {PI_selected} >Pistachio     </option> 
   </select>''')

    t1_checked = 'checked' if topping1 !='' else ''
    t2_checked = 'checked' if topping2 !='' else ''
    t3_checked = 'checked' if topping3 !='' else ''
    t4_checked = 'checked' if topping4 !='' else ''
                                                                                #checkbox
    print(F'''<tr><td><b>Select Topping<td> 
              <input type="checkbox" name="topping1" value="hotFudge"     {t1_checked} > Hot Fudge
              <input type="checkbox" name="topping2" value="sprinkles"    {t2_checked} > Sprinkles
              <input type="checkbox" name="topping3" value="nuts"         {t3_checked} > Nuts
              <input type="checkbox" name="topping4" value="whippedCream" {t4_checked} > Whipped Cream
    ''')

    MC_checked = 'checked' if creditCard=='MAST' else ''
    VI_checked = 'checked' if creditCard=='VISA' else ''
    AX_checked = 'checked' if creditCard=='AMEX' else ''
    DS_checked = 'checked' if creditCard=='DISC' else ''
                                                                               #radio button
    print(F'''<tr><td><b>Credit Card<td>                                    
              <input type="radio" name="creditCard" value="MAST" {MC_checked} > Master Card
              <input type="radio" name="creditCard" value="VISA" {VI_checked} > Visa
              <input type="radio" name="creditCard" value="AMEX" {AX_checked} > American Express
              <input type="radio" name="creditCard" value="DISC" {DS_checked} > Discover
   ''')

    print('''
        <tr>
            <td colspan=2>
            <input type="submit" name=submit value="  Place Order " />
            <input type="reset"  name=cancel value="Cancel"         />
        </table>
        </fieldset>
        </form>
    ''') 

    if params and not msg:                                # \ is continuation line
        msg = '<b>You have entered:</b> <br>\n'  \
            + firstname +' '+ lastname +'<br>\n' \
            + address +'<br>\n'                  \
            + brand +'<br>\n'                    \
            + ''.join(flavor) +'<br>\n'          \
            + topping1 +' '+ topping2 +' '+ topping3 +' '+ topping4 +'<br>\n' \
            + creditCard      
       
    print("<p style='color:red'>" + msg + '</p>')
    print('</body>')
    print('</html>')
#-------------------------------------------------------------------------------------
# Main code
#-------------------------------------------------------------------------------------

#if params:                                      #if data was entered in the form 
#    validate()                                  #call validate function                            
    
display()                                       #call display function



#print(elements)                                 #test only 
#print('<br>')                               
def isSelfCall():
    import os
    requesting_url = os.environ.get('HTTP_REFERER') or ''
    requested_url  = os.environ.get('REQUEST_URI')  or ''
    if requested_url in requesting_url:
        return(True)
    else:
        return(False)
print('Self call?', isSelfCall()) 





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