#!/usr/bin/python3
#####################################################################################
# Create and use a shopping cart (sample code)
# This shopping cart does not use cookies, session variables, nor database
# A cart is created using appName_IPaddr
#####################################################################################
import cgi
import cgitb
import shopcartFunc                                 #import custom shopCart functions

cgitb.enable()
 
print('Content-type: text/html \n')

appName = 'XYZ'                                     #enter a unique application name or leave it XYZ

elements  = cgi.FieldStorage()
option    = elements.getvalue('opt')      or ''     #get the button option pressed 
itemName  = elements.getvalue('item')     or ''     #from query string       
itemPrice = elements.getvalue('price')    or ''     #from query string      
itemQty   = elements.getvalue('quantity') or ''     #from input field
itemCmt   = elements.getvalue('comment')  or ''     #from input field

itemErr = ''
qtyErr  = ''
error   = ''
msg     = ''

#-- Validate --------------------------------------------------------------------------------
if option == 'add':                                     #validate input fields
    if not itemQty or int(itemQty) <= 0:
        qtyErr  = '*'
        error   = 'Please enter quantity'
    if not itemName:
        itemErr = '*'
        error   = 'Please choose a shopping cart item and enter quantity'
if option == 'del':
     if not itemName:
        itemErr = '*'
        error   = 'Please choose a shopping cart item to delete'
           
#-- Process --------------------------------------------------------------------------------
if not error:                                           #if no validation errors
    shopcartFunc.accessCart(appName)                    #Create new or access existing shopping cart
    if option == 'add':                                 #add an item to shopping cart                        
        values = '$'+ str(itemPrice) +', '+ itemQty
        if itemCmt: values += ', '+ itemCmt
        shopcartFunc.setCartItem(itemName,values)
        msg = F"Item {itemName} added to your shopping cart"                      
    if option == 'del':                                 #delete an item from shopping cart
        shopcartFunc.delCartItem(itemName)                                                                    
        msg = F"Item {itemName} deleted from your shopping cart"                      
    if option == 'clear':                               #delete entire shopping cart 
        shopcartFunc.deleteCart()
        itemName  = ''
        itemPrice = ''                   
        msg = "Your shopping cart has been cleared"                      

#--- Display HTML Page ------------------------------------------------------------------------
print("""
    <html>
    <head>
    <title>Shopping Cart Example</title>
    <style>
        button           {width:110px; color:white; background-color:2C2C2C}
        #button2         {width:110px; color:white; background-color:green; height:30px}
        #table1 td       {border:1px solid black; width:120; background-color:lightgray; cursor:pointer} 
        #table1 td:hover {background-color:red; color:white} 
       .readonly         {background-color:lightgray; color:red; font:bold}
        span             {color:red}}
    </style> 
    </head>
    <body bgcolor=lightyellow>
    <img src=img/emptyCart.jpg id=swap style='position:absolute; top:40; right:10; width:300; height:300'>
    <h2>Shop From the List of Products Below</h2>
    <br>
""")

print(F"<form method=post name=frm >")  

#--- Below data should come from a database table ------------------------------------------
print("""
    <fieldset style='width:720px'>
    <table id=table1 >
    <tr><th>Choose Item
    <td onClick="document.frm.item.value='Apples';   document.frm.price.value='1.49'"
        onMouseOver="document.getElementById('swap').src='img/Apples.jpg'">            Apples  $1.49</td> 
    <td onClick="document.frm.item.value='Oranges';   document.frm.price.value='1.25'"
        onMouseOver="document.getElementById('swap').src='img/Oranges.jpg'">           Oranges $1.25</td> 
    <td onClick="document.frm.item.value='Peaches';   document.frm.price.value='1.99'"
        onMouseOver="document.getElementById('swap').src='img/Peaches.jpg'">           Peaches $1.99</td>
    <td onClick="document.frm.item.value='Bananas';   document.frm.price.value='0.99'"
        onMouseOver="document.getElementById('swap').src='img/Bananas.jpg'">           Bananas $0.99</td>
    <td onClick="document.frm.item.value='Pears';     document.frm.price.value='1.79'"
        onMouseOver="document.getElementById('swap').src='img/Pears.jpg'">             ears   $1.79</td>
    <tr><th>
    <td onClick="document.frm.item.value='Potatoes';  document.frm.price.value='0.99'"
        onMouseOver="document.getElementById('swap').src='img/Potatoes.jpg'">          Potatoes  $0.99</td> 
    <td onClick="document.frm.item.value='Tomatos';   document.frm.price.value='1.49'"
        onMouseOver="document.getElementById('swap').src='img/Tomatos.jpg'">           Tomatos   $1.49</td>  
    <td onClick="document.frm.item.value='Spinach';   document.frm.price.value='2.29'"
        onMouseOver="document.getElementById('swap').src='img/Spinach.jpg'">           Spinach   $2.29</td>  
    <td onClick="document.frm.item.value='Carrots';   document.frm.price.value='1.19'"
        onMouseOver="document.getElementById('swap').src='img/Carrots.jpg'">           Carrots   $1.19</td>  
    <td onClick="document.frm.item.value='Cucumbers'; document.frm.price.value='1.29'"
        onMouseOver="document.getElementById('swap').src='img/Cucumbers.jpg'">         Cucumbers $1.29</td>
    <tr><th>
    <td onClick="document.frm.item.value='Milk';    document.frm.price.value='3.49'"
        onMouseOver="document.getElementById('swap').src='img/Milk.jpg'">              Milk    $3.49</td> 
    <td onClick="document.frm.item.value='Yogurt';  document.frm.price.value='1.49'"
        onMouseOver="document.getElementById('swap').src='img/Yogurt.jpg'">            Yogurt  $1.49</td>  
    <td onClick="document.frm.item.value='Cheese';  document.frm.price.value='5.99'"
        onMouseOver="document.getElementById('swap').src='img/Cheese.jpg'">            Cheese  $5.99</td>  
    <td onClick="document.frm.item.value='Juice';   document.frm.price.value='2.99'"
        onMouseOver="document.getElementById('swap').src='img/Juice.jpg'">             Juice   $2.99</td>  
    <td onClick="document.frm.item.value='Cookies'; document.frm.price.value='6.99'"
        onMouseOver="document.getElementById('swap').src='img/Cookies.jpg'">           Cookies $6.99</td>
    </table>
""")

#--- Print form input fields -----------------------------------------------------------
print(F"""
    <table>
    <tr><td>                <td> <input type=text   name=item     value='{itemName}'  readonly class=readonly>                            <span>{itemErr}</span> 
    <tr><td><b>Item Price...<td> <input type=text   name=price    value='{itemPrice}' readonly class=readonly>           
    <tr><td><b>Quantity.....<td> <input type=number name=quantity value='{itemQty}'> <span>{qtyErr}</span> 
    <tr><td><b>Comment..... <td> <textarea          name=comment  rows=4 cols=84>{itemCmt}</textarea> 
    </table>
    <font color=red>{error}  </font>
    </fieldset>
    <br>
    <button type=submit name=opt value='add'>   Add Item    </button>
    <button type=submit name=opt value='del'>   Delete Item </button>
    <button type=submit name=opt value='view'>  View Cart   </button>
    <button type=submit name=opt value='clear'> Clear Cart  </button>
    </form>
    <button type=button id=button2 onclick="location.href='shopcheckout.py'"> Checkout </button>      <!--redirect to another page-->
    <font color=red> {msg} </font>
 """)

#--- Display Shopping Cart ---------------------------------------------------------------------
cartId    = shopcartFunc.getCartId() 
cartItems = shopcartFunc.getCartItems()                                 #get all items as a dictionary

if option=='view':                                                      #if option is view 
    if cartItems:    
        print(F"""<h4><i>Cart Id:</i> {cartId} </h4> 
                  <table border=2 bgcolor=tan>
                  <tr bgcolor=cccccc><th><i><nobr>Item<th width=500><i>Price & Quantity<th><i>Delete</th>
              """)        
        for name in sorted(cartItems):                                  #loop thru the cart items
            print("<tr><td><b>",name,"<td width=500>",cartItems[name])  #print the item name & values
            print(F"<td><a href=shop2.py?opt=del&item={name}>")       #anchor to current script
            print("<img src=img/delete.png height=20 width=35></a>")    #add delete button

        print("</table>")
    
    else:
        print("<h4>Your Shopping Cart is Empty</h4>")
    
if cartItems: image = 'img/fullcart.jpg'
else:         image = 'img/emptycart.jpg'    
print(F"<script>document.getElementById('swap').src='{image}'</script>") 





#=== link to see the python code =================================================
import os, sys
sys.path.insert(0,'/home/s/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
#=================================================================================