#!/usr/bin/python3
#=========================================================================================
# Read a chopping cart (CSV format), add items to it, rewrite shopping cart
#=========================================================================================
 
print("Content-Type: text/html \n")          #required http response header (w/ extra line)
print('<br><br>')

fileIn  = '/home/sultans/web/python/demo/zhomework_answers/shopcart_io_hide/shop_csv_in.txt'     #input file
fileOut = '/home/sultans/web/python/demo/zhomework_answers/shopcart_io_hide/shop_csv_out.txt'    #output file

shopCart = []
 
#--- read from file -------------------------------------------------------

inputFH = open(fileIn,'r')                          #Open file for reading     
string = inputFH.read()                             #read entire file into a string
lines  = string.splitlines()                        #split the string into a list of lines
inputFH.close()                                     #close the file

#--- load into list of dictionaries ---------------------------------------

line1 = lines[0]                                    #take line 1 (the header)   
keys  = line1.split(',')                            #split headers on ,
del lines[0]                                        #get rid of the headings                         

for line in lines:                                  #loop thru the rest of the lines 
    item = {}                                       #create an empty dictionary
    values = line.split(',')                        #split each line into values
    for x in range(len(keys)):                      #loop thru the keys
        key   = keys[x]                             #get the key
        value = values[x]                           #get the value
        item[key] = value                           #build the dictionary key/value
    shopCart.append(item)                           #append the dictionary to the shopping cart

print(shopCart)
print('<br>')

#--- update the shopping cart ---------------------------------------------

item5 = {'ITEM':"cherry", 'DESCRIPTION':"Bing Cherries",   'QUANTITY':2, 'PRICE':2.49}
item6 = {'ITEM':"grape",  'DESCRIPTION':"Riesling grapes", 'QUANTITY':1, 'PRICE':1.79}

shopCart.append(item5)                              #add item to shopping cart
shopCart.append(item6)

print(shopCart)
print('<br>')

#--- write back to file ---------------------------------------------------

outputFH = open(fileOut,'w')                        #Open file for writing
rec      = ','.join(keys)                           #concatenate all the headers
outputFH.write(rec + '\n')                          #write the headers

for dict in shopCart:                               #loop thru the shopping cart
    values = dict.values()                          #get each dict item values
    rec = ''
    for value in values:                            #loop thru the values
        rec += str(value) + ','                     #build the rec with value and ,
    rec = rec.rstrip(',')                           #strip the last comma
    outputFH.write(rec + '\n')                      #write the values

outputFH.close()                                    #close the file




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