#!/usr/bin/python3
#####################################################################################
# Set and Get Session Variables
# Starting and ending a session must be called before generating any HTML output
#####################################################################################
import cgi
import cgitb
from datetime import datetime
import sessionFunc                               #import custom session functions

cgitb.enable()
 
elements = cgi.FieldStorage()

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

sessionId = ''

if option == 'start':                           #start a session                        
    sessionId = sessionFunc.startSession()      #must be called before any HTML output
    name  = "_session_start_time"
    time  = str(datetime.now())                 #date and time
    value = time[0:19]                          #get rid of milliseconds
    sessionFunc.setSessionVar(name,value)       #call the setSessionVar function                

if option == 'set' and name != '':              #set a session variable
    sessionFunc.setSessionVar(name,value)       #call the setSessionVar function

if option == 'del' and name != '':              #delete a session variable
    sessionFunc.delSessionVar(name)             #call the delSessionVar function

if option == 'end':                             #end a session
    sessionFunc.endSession()                    #must be called before any HTML output
                                                  
if not sessionId: 
    sessionId = sessionFunc.getSessionId()
    if not sessionId:
        sessionId = 'no session' 

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

print(F"""
    <html>
    <head>
    <title>Session Variables Set/Get</title>
    </head>
    <body bgcolor=lightyellow>
    <h2>Your Session Variables Are:</h2>
    <h4>Session Id: {sessionId} </h4> 

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

sessionVars = sessionFunc.getSessionVars()                  #call the getSessionVars() function

start = sessionVars.get('_session_start_time')
if start:
    start = datetime.strptime(start,'%Y-%m-%d %H:%M:%S')    #original start time from session var
    now   = datetime.now()                                  #now
    delta = now - start
    print("<tr bgcolor=cccccc><th><i>SESSION DURATION<td>",str(delta)[0:9])
     
for name in sorted(sessionVars):                            #loop thru the session variables dictionary
    print("<tr><td><b>",name,"<td>",sessionVars[name])      #print variable name & value

print("</table>")
    
if not sessionVars:
    print("<h4>There are no session variables for your session</h4>") 
    
if option=='end':
    print("<h3>Your session has ended</h3>") 
    




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