######################################################################################################
# This set of function allows you to create and use a shopping cart
# functions: accessCart, clearCart, deleteCart 
#            setCartItem, getCartItem, getCartItems, delCartItem
# To create a shopping cart, call createCart() and pass it an application name 1-4 characters
# Each item in shopping cart should have a name, and a set of values comma delimited
# it is up to you to determine the order and meaning of the item values 
#  (example: 'apple','Macintosh,3,1.25') 
######################################################################################################
import os

filepath  = '/home/sultans/tmp/py-shopcarts/'
cartId    = ""
filename  = ""                                    
#====================================================================================
# accessCart(): Create a new shopping cart or access an existing one
#               Creates an associated shopping cart file using: appName+clientIP 
#         args: application name (if none is passed, use 'XYZ') 
#      returns: the shopping cart id
#====================================================================================
def accessCart(appName='XYZ'):
    global cartId, filename

    appName  = appName[0:4]                             #only take first 4 characters
    appName  = appName.replace(' ','_')
    clientIP = os.environ.get('REMOTE_ADDR') or '123.123.123.123'
    clientIP = clientIP.replace('.','-')
    cartId   = appName  +'_'+ clientIP
    filename = filepath + cartId                        #create a full filename
        
    if not (os.path.exists(filename)):
        file = open(filename,'w')                       #create an associated file if not exist
        file.close()
        
    return (cartId)                                     # return the cartId

#====================================================================================
# getCartId(): get the shopping cart Id
#     returns: the cart Id or null if no cart
#====================================================================================
def getCartId():
    
    if not cartId: return ""
    return (cartId)                                  #return the cartId

#====================================================================================
# setCartItem(): insert/update a shopping cart item
#            args: name, value, 
#====================================================================================
def setCartItem(name, value):

    cartDict = read_file()
    cartDict[name] = value                              #insert/update shopping cart item
    write_file(cartDict)
    
#====================================================================================
# getCartItems(): Get all items in shopping cart  
#        returns: all shopping cart items as a dictionary
#====================================================================================
def getCartItems():

    cartDict = read_file()
    return cartDict 

#====================================================================================
# getCartItem(): Get a single shopping cart item
#          args: cart item name
#       returns: cart item value  
#====================================================================================
def getCartItem(name):

    cartDict = read_file()
    value = cartDict.get(name)
    return value

#====================================================================================
# delCartItem(): delete a single shopping cart item
#          args: cart item name
#====================================================================================
def delCartItem(name):
    
    cartDict = read_file()
    try:    del cartDict[name]                              #delete shopping cart item
    except: pass                                            #if fails, do nothing
    write_file(cartDict)

#====================================================================================
# clearCart(): clear all shopping cart items - does not delete the file
#====================================================================================
def clearCart():
    
    cartDict = {}                                       #empty cartDict
    write_file(cartDict)

#====================================================================================
# deleteCart(): Delete a shopping cart
#    Delete the shopping cart file  
#====================================================================================
def deleteCart():

    if os.path.exists(filename):
        os.remove(filename)                                 #delete the file

        
#====================================================================================
# read_file(): Read all shopping cart items from file and build cart dictionary
#     returns: all shopping cart items as a dictionary
#====================================================================================
def read_file():
    dict = {}
    
    if not filename:
        return dict 

    try:
        file = open(filename, 'r')                      #open file for reading
        content = file.read()                           #read entire file into a string     
        file.close()
    except:
        content = ''

    items = content.splitlines()                         #split the lines
    for item in items:
        nameValue = item.split('=')                       #split on '=' sign
        name   = nameValue[0]
        values = nameValue[1]
            
        dict[name] = values                              #add to dictionary
            
    return dict 

#====================================================================================
# write_file(): Write all shopping cart items from dictionary into file
#         args: shopping cart dictionary
#====================================================================================
def write_file(dict):
    global filename

    filename  = filepath + cartId
    file = open(filename, 'w')                          #open file for writing

    for (name,value) in dict.items():
        file.write(name + '=' + value + '\n')           #write each variable in file         

    file.close()
 
#====================================================================================