#!/usr/bin/env python3
#####################################################################################
# Set and Get Cookies
# Set cookies must be done/written before any html output
#####################################################################################
import cookieFunc                               #import custom cookie functions
import cgi
import cgitb
cgitb.enable()
 
elements = cgi.FieldStorage()

option = elements.getvalue('option') or ''      #get the option param (at the end of URL?option=set) 
name   = elements.getvalue('cookie') or ''      #get all the form fields
value  = elements.getvalue('value')  or ''
expire = elements.getvalue('expire') or 0

if option == 'set' and name:              		#set a cookie
    cookieFunc.setCookie(name,value,expire)     #call the setCookie function
    print('Location:', 'cookie.py' )            #redirect to self to ensure that cookie is sent to client

print('Content-Type: text/html')
print('\n')                                     #IMPORTANT: end the headers

print("""
    <html>
    <head>
    <title>Cookies Set/Get</title>
    </head>
    <body bgcolor=lightyellow>
    <h2>Your Cookies Are:</h2>

    <table border=2 bgcolor=tan>
    <tr bgcolor=cccccc><th><i><nobr>Cookie Name<th><i>Cookie Value</th>    
""")

cookies = cookieFunc.getCookies()                       #call the getCookies() function
if cookies:
    for name in sorted(cookies):                        #loop thru the cookies dictionary
        print("<tr><td><b>",name,"<td>",cookies[name])  #print cookie name & value

print("</table>")
    
if not cookies:
    print("<h4>There are no cookies, or browser does not accept cookies</h4>") 
    


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