#!/usr/bin/env python
# coding: UTF-8
#
## @package cookie
#
# CGI cookie example - Chapter 18 - cookie.cgi
#
# @author John Goerzen
# @since 19/05/2021
# @see http://187.52.54.51/emmonks/redesii/Python_Sockets/18/cookie.cgi
# @see https://www.amazon.com/Foundations-Python-Network-Programming-Brandon/dp/1430258543
# @see https://github.com/apress/foundations-of-python-network-programming-14
#
import cgitb
cgitb.enable()

import cgi, os, sys, urllib
from http.cookies import SimpleCookie

def getCookie():
    if os.environ.has_key('HTTP_COOKIE'):
        cookiestring = os.environ['HTTP_COOKIE']
    else:
        cookiestring = ''
    return SimpleCookie(cookiestring)

def dispCookie():
    cookie = getCookie()
    print ("\t\tFound the following cookies:\n\t\t<UL>")
    foundcookies = 0
    for key in cookie.keys():
        morsel = cookie[key]
        print ("\t\t\t<LI>%s: %s</LI>" % (cgi.escape(key), cgi.escape(morsel.value)))
        foundcookies += 1
    print ("\t\t</UL>")
    if foundcookies:
        print ("""
        <P><A HREF="%s?action=delCookie">Click here</A>
        to delete the testcookie.</P>
        """) % os.environ['SCRIPT_NAME']

def setCookie(value, maxage):
    cookie = getCookie()
    cookie['testcookie'] = value
    cookie['testcookie']['max-age'] = maxage
    print (cookie.output())
    
def main():
    print ("Content-type: text/html")
    form = cgi.FieldStorage()
    action = form.getfirst('action')
    if action == 'setCookie':
        setCookie(form.getfirst('cookieval'), 60*60*24*365)
        print ("")                              # Signal end of the headers
        print ("""
        <HTML>
            <HEAD><TITLE>Cookie Set</TITLE></HEAD>
        <BODY>
            The cookie has been set.
            Click <A HREF="%s">here</A> to return to the main page.
        </BODY>
        </HTML>
        """) % os.environ['SCRIPT_NAME']
    elif action == 'delCookie':
        setCookie('fake', 0)
        print ("")                              # Signal end of the headers
        print ("""
        <HTML>
            <HEAD><TITLE>Cookie deleted</TITLE>
        </HEAD>
        <BODY>
            The cookie has been deleted. 
            Click <A HREF="%s">here</A> to return to the main page.
        </BODY>
        </HTML>
        """) % os.environ['SCRIPT_NAME']
    else:
        print ("")
        print ("""
        <HTML>
        <HEAD>
            <TITLE>CGI Cookie Example</TITLE>
        </HEAD>
        <BODY>
        """)

        dispCookie()

        print ("""
        <FORM METHOD="GET" ACTION="%s">
        """) % os.environ['SCRIPT_NAME']

        for value in ['Red', 'Green', 'Blue', 'White', 'Black']:
            print ("""
            <INPUT TYPE="radio" NAME="cookieval" VALUE="%s"> %s <BR>
            """) % (value, value)

        print ("""
            <INPUT TYPE="submit" NAME="action" VALUE="setCookie">
        </FORM>
        </BODY>
        </HTML>""")

if __name__=="__main__":
    sys.exit(main())