#!/usr/bin/python3
###################################################################################
# Read all cookies
# Using HTTP header "Cookie:"
###################################################################################
import os
import cgitb
from urllib import parse

cgitb.enable()

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

print("<h2>Reading Cookies - Using HTTP Headers</h2>")

cookiesStr = os.environ.get('HTTP_COOKIE')          #obtain the HTTP cookies

if cookiesStr is None:                              #if there are no cookies
    print("<h3>There are no cookies.</h3>")
    exit() 

print(cookiesStr, '<br><br>')                       #print(all cookies, '; ' delimited

#==========================================================================
# display_cookies(): Manually parse the cookie string
#                    Split by '; ' for each cookie
#                    Split by '='  for each name=value pair
#==========================================================================
def display_cookies(cookiesStr):

    cookiesList = cookiesStr.split('; ')

    print('<table border=1>')
    print('<tr bgcolor=tan><th>Cookie Name<th>Cookie Value</tr>')

    for cookie in cookiesList:
        (name, value) = cookie.split('=',1)                     #split on first =
        print('<tr>', end='')
        print('<td>', name, end='')                             #cookie name
        value_decoded = parse.unquote(value)		            #decode the name (if encoded)
        print('<td><b>Encoded:</b>', value, end='')             #cookie value (encoded)
        print('<br><b>Decoded:</b>', value_decoded, '</td>')    #cookie value (decoded)

    print('</table>')
#==========================================================================

display_cookies(cookiesStr)



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