#!/usr/bin/python3
#####################################################################################
# Create and use a shopping cart (sample code)
# This shopping cart does not use cookies, nor session variables
# 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

if isinstance(itemName,  list): itemName  = itemName[0]         #Python bug? returning a list of 2 elements
if isinstance(itemPrice, list): itemPrice = itemPrice[0]        #Python bug? if so, take the first one

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

#-- Validate --------------------------------------------------------------------------------
if option == 'add':                                     #validate input fields
    if not itemQty or int(itemQty) <= 0:
        qtyErr  = '*'
        error   = 'Please enter item quantity'
           
#-- 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) +', '+ str(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 Input Form ------------------------------------------------------------------------
print(F"""
    <html>
    <head>
    <title>Shopping Cart Example</title>
    <style>
        button    {{width:100px; color:white; background-color:2C2C2C}}
        .button2  {{background-color:green;}}
        .readonly {{background-color:lightgray; color:red; font:bold}}
        span      {{color:red}}
    </style> 
    </head>
    <body bgcolor=lightyellow>
    <h2>Add Items to your Shopping Cart</h2>
    <br>
    <form method=post name=frm > 
    <fieldset style='width:560px'>
    <table>
    <tr><td><b>Item ........<td> <input type=text   name=item     value='{itemName}'  readonly class=readonly>
    <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}' min=1> <span>{qtyErr}</span> 
    <tr><td><b>Comment..... <td> <textarea          name=comment  rows=6 cols=60>{itemCmt}</textarea> 
    </table>
    </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>
    <br><br>
    <button type=button class=button2 onclick="location.href='shop.py'">         Return to Shopping </button>
    <button type=button class=button2 onclick="location.href='shopcheckout.py'"> Go to Checkout     </button>
    </form>
    <font color=red>{error} {msg}</font> 
 """)

#-- Display Shopping Cart ---------------------------------------------------------------------
if option=='view':                                                      #if option is view 
    cartId    = shopcartFunc.getCartId() 
    cartItems = shopcartFunc.getCartItems()                             #get all items as a dictionary

    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=shopcart.py?opt=del&item={name}>")       #anchor to current script
            print("<img src=img/delete.png height=20 width=35></a>")    #add delete icon

        print("</table>")    
    else:
        print("<h4>Your Shopping Cart is Empty</h4>")
        itemName = '' 
       
if itemName: 
    image = 'img/'+ itemName + '.jpg' 
else:        
    image = 'img/emptyCart.jpg'
print(F"<img src={image} style='position:absolute; top:40; right:50; width:300; height:300'>")




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