#!/usr/bin/python3
#=====================================================================================
# A typical shopping page with shopping cart stored in a cookie
#=====================================================================================
import os
import cgi                           #import cgi module 
import cgitb                         #import cgi traceback module for error handling
import cookieFunc                    #import cookie functions

cgitb.enable()                       #activate the cgi traceback error handling 

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

log   = elements.getvalue('log')             #obtain log via URL?log=OK 
login = cookieFunc.getCookie('login');       #obtain login cookie 

if not (log or login):                                                 #if no login cookie
    print('Location: /~sultans/python/demo/5cookie/cookieLogin.py')    #redirect to login page
    print('\n')                                                        #end of headers
    exit()

item   = elements.getvalue('item')    or ""     #text field
value  = elements.getvalue('value')   or 1      #text field 
add    = elements.getvalue('add')     or ""     #add  button             
view   = elements.getvalue('view')    or ""     #view button 
logout = elements.getvalue('logout')  or ""     #logout button 

html = ''

#-------------------------------------------------------------------------------------
# Function to add items to shopping cart
#-------------------------------------------------------------------------------------
def add_to_cart():

    global html;

    if (item == ''): return                             #if none is given, return

    cart = get_cart('myCart');                          #get the cart from a cookie

    cart[item] = str(value);                            #add the new item to cart    

    expiration = 7;                                     #7 days from now in seconds

    set_cart(cart,'myCart',expiration);                 #save the cart in a cookie 

    html = "<b>"+ str(value) +" "+ item +" </b>have been added to your shopping cart" 

#-------------------------------------------------------------------------------------
# Function display entire cart
#-------------------------------------------------------------------------------------
def view_cart():

    global html;

    cart = get_cart('myCart');                                  #get the cart from a cookie

    html  = "<table border=2 bgcolor=f0f0f0> \n"
    html += "<tr bgcolor=cyan><th><i>Item Name<th><i>Quantity</th> \n"

    for item in cart:                                           #for every item in the cart
        html += "<tr><td>"+ item +"<td>"+ cart[item] +"\n";     #print the item name and value
    
    html += "<tr><td colspan=2 bgcolor=cyan><b>"+ str(len(cart)) +"</b> items in cart \n"
    html += "</table>"

#-------------------------------------------------------------------------------------
# Get shopping cart from a single cookie, and build a cart dictionary
#-------------------------------------------------------------------------------------
def get_cart(cartName):

    cart = {}                                       #empty dictionary
    
    cart_string = cookieFunc.getCookie(cartName)    #get shopping cart from the cooklie    
    if not cart_string:
        return(cart)

    cart_list  = cart_string.split('|')             #split string cart on |
    for item in cart_list:                          #for every item in the cart list
        name_value = item.split(':')                #split each item on :
        itemName  = name_value[0]
        itemValue = name_value[1]
        if (itemName != ''):                        #if there is an item
            cart[itemName] = itemValue;             #add it with its value to the cart object
    return(cart);                                   #return the shopping cart dictionary
    
#-------------------------------------------------------------------------------------
# Take a shopping cart dictionary and store it in a cookie
#-------------------------------------------------------------------------------------
def set_cart(cart,cartName,expire):

    cart_list = []                                          #empty list
    
    for item in cart:                                       #for every item in the cart             
        name_value = item +':'+ cart[item]                  #join the name and value using :
        cart_list.append(name_value)
         
    cart_string = '|'.join(cart_list)                       #join all items using | 

    cookieFunc.setCookie(cartName, cart_string, expire);    #save the cart in a cookie    

#-------------------------------------------------------------------------------------
# Function to log out and delete the cookie
#-------------------------------------------------------------------------------------
def log_out():

    cookieFunc.setCookie('login', '', -999);                #delete the login cookie    
    print('Location: /~sultans/python/demo/5cookie/')       #redirect to directory listing
    print('\n')                                             #end of headers
    exit()

#-------------------------------------------------------------------------------------
# display the page
#-------------------------------------------------------------------------------------
def display():

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

    print("""
        <html>
        <head>
        <title>Cookie Check</title>
        <style> td {cursor:pointer} </style>
        </head>

        <body bgcolor=lightyellow>
        <h1 align=center>Welcome to our Store 
    """)
#   print(userCookie)
    print("""
        </h1>
        <h3>We Sell...</h3>
        <table cellpadding=2 id=products>
        <tr bgcolor=cccccc><td>Apples<td>Pears<td>Oranges<td>Grapes<td>Strawberries<td>Bananas<td>Apricots<td>Peaches</tr> 
        <tr bgcolor=cccccc><td>Tables<td>Chairs<td>Lamps<td>Desks<td>Wall Units<td>Chests<td>Sofas<td>Beds</tr>
        <tr bgcolor=cccccc><td>TVs<td>DVDs<td>iPhones<td>iPods<td>Computers<td>Monitors<td>Printers<td>Scanners</tr>
        <tr bgcolor=cccccc><td>Shirts<td>Pants<td>Skirts<td>Hats<td>Socks<td>Shoes<td>Ties<td>Belts</tr>
        </table>
        And much much more...
        <h3>Add any item to your shopping cart</h3>
    """)
    print("<form method=post name=frm >")
    print("""
        <table>
        <tr><td>Click item into your cart<td> <input type=text   name=item id=item readonly>
        <tr><td>Enter quantity<td>            <input type=number name=value>
        </table>
        <br>
        <input type=submit name=add    value="Add to Cart">
        <input type=submit name=view   value="View Cart">
        <input type=submit name=logout value="Log Out">
        </form>
        <hr>
    """)
    print(html)
    print("""
        <script>
        //JavaScript code to allow cliking on item and moving it to text field
            buy   = document.getElementById('item')                         //the item text field
            prod  = document.getElementById('products')                     //the table of products
            items = prod.getElementsByTagName('td')                         //each product
            for (idx in items)
            {
                item = items[idx]
                item.onclick = function() {buy.value = this.textContent}    //copy name of the item into the text field 
            }
        </script>
        </body>
        </html>
    """)

#-------------------------------------------------------------------------------------
# Main code
#-------------------------------------------------------------------------------------
if add:                         #if add button is pressed
    add_to_cart();

if view:                        #if view button is pressed
    view_cart();

if logout:                      #if logout button is pressed
    log_out();

display();
    


#=== link to see the python code ================================================
import os
import 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
#================================================================================