#!/usr/bin/python3
#=========================================================================================
# Read a chopping cart (JSON format), add items to it, rewrite shopping cart
#=========================================================================================
import json
 
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_json_in.txt'     #input file
fileOut = '/home/sultans/web/python/demo/zhomework_answers/shopcart_io_hide/shop_json_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
inputFH.close()                                     #close the file

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

shopCart = json.loads(string)                       #convert JSON string input to Python list of dictionary 

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

json = json.dumps(shopCart, indent=4)               #convert list of dictionaries to JSON string

outputFH = open(fileOut,'w',newline='\n')           #Open file for writing, preserve newlines
outputFH.write(json)                                #write the entire file
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
#=================================================================================