######################################################################################################
# This set of functions simulate a web session
# Must import cookieFunc 
# functions: startSession, endSession, getSessionId
#            setSessionVar, getSessionVar, getSessionVars, delSessionVar
# startSession() and endSession() functions must be called before generating any HTML output 
######################################################################################################
import os
from random import randrange
import cookieFunc                               #MUST import cookieFunc

filepath  = '/home/sultans/tmp/py-sessions/'    #file directory to store session variables
sessionId = ''                                  #for first time, will be randomly generated 
                                    
#====================================================================================
# startSession(): Start a new web session
#    A random number is generated and assigned to sessionId = 'sess'+number
#    A cookie is saved as PYSESSID=sessionId
#    A file with the name of sessionId is also created and saved in the directory
#    return the sessionId
# PS. This function must be called before any HTML output since it uses cookies 
#====================================================================================
def startSession():
    global sessionId

    sessionId = cookieFunc.getCookie('PYSESSID')        #get cookie PYSESSID
    if (not sessionId):
        rand = randrange(10000000,99999999)             #generate a random number
        sessionId = 'sess' + str(rand)                  #generate a session id as 'sess'+rand
        cookieFunc.setCookie('PYSESSID',sessionId)      #save it in a cookie
        filename = filepath + sessionId                 #create a full filename
        file     = open(filename,'w+')                  #create an associated file if not exist
        file.close()
        
    return (sessionId)                                  # return the sessionId

#====================================================================================
# getSessionId(): get the session Id
#        returns: the session Id or null if no session
#====================================================================================
def getSessionId():
    global sessionId

    sessionId = cookieFunc.getCookie('PYSESSID')        #get cookie PYSESSID        
    return (sessionId)                                  #return the sessionId

#====================================================================================
# setSessionVar(): Set a session Variable
#            args: name, value 
#====================================================================================
def setSessionVar(name, value):
    global sessionId

    if (not sessionId):
        sessionId = cookieFunc.getCookie('PYSESSID')
        if (not sessionId):
            return('You do not have an active web session. Call startSession() first')

    sessionDict = read_file()
    sessionDict[name] = value                           #insert/update session variable
    write_file(sessionDict)
    
#====================================================================================
# getSessionVars(): Get all session variables  
#          returns: all session variables as a dictionary
#====================================================================================
def getSessionVars():
    global sessionId

    if (not sessionId):
        sessionId = cookieFunc.getCookie('PYSESSID')
        if (not sessionId):
            empty = {}                                  #empty dictionary
            return empty              

    sessionDict = read_file()
    return sessionDict 

#====================================================================================
# getSessionVar(): Get a single session variable
#            args: session variable name
#         returns: session variable value  
#====================================================================================
def getSessionVar(name):
    global sessionId
    
    if (not sessionId):
        sessionId = cookieFunc.getCookie('PYSESSID')
        if (not sessionId):
            return ''

    sessionDict = read_file()            
    value = sessionDict.get(name)
    return value

#====================================================================================
# delSessionVar(): delete a single session variable
#            args: session variable name
#====================================================================================
def delSessionVar(name):
    global sessionId
    
    if (not sessionId):
        sessionId = cookieFunc.getCookie('PYSESSID')
        if (not sessionId):
            return('You do not have an active web session. Call startSession() first')

    sessionDict = read_file()
    try:    del sessionDict[name]                           #delete session variable
    except: pass                                            #if fails, do nothing
    write_file(sessionDict)

#=====================================================================================
# endSession(): End a web session
#    Delete the PYSESSID cookie and delete the session file  
# PS. This function must be called before any HTML output since it deletes the cookie 
#=====================================================================================
def endSession():
    global sessionId

    if (not sessionId):
        sessionId = cookieFunc.getCookie('PYSESSID')
        if (not sessionId):
            return('You do not have an active web session. Call startSession() first')

    cookieFunc.setCookie('PYSESSID',sessionId,-9999)        #delete the cookie
    filename = filepath + sessionId
    if os.path.exists(filename):
        os.remove(filename)                                 #delete the file
        
#====================================================================================
# read_file(): Read all session variables from file and build session dictionary
#     returns: all session variables as a dictionary
#====================================================================================
def read_file():
    dict = {}
    
    filename  = filepath + sessionId
    try:
        file = open(filename, 'r')                      #open file for reading
        content = file.read()                           #read entire file into a string     
        file.close()
    except:
        content = ''

    vars = content.splitlines()                         #split the lines
    for var in vars:
        nameValue = var.split('=')                      #split on '=' sign
        name  = nameValue[0]
        value = nameValue[1]
        dict[name] = value                              #add to dictionary
            
    return dict 

#====================================================================================
# write_file(): Write all session variables from dictionary into file
#         args: session variables dictionary
#====================================================================================
def write_file(dict):

    filename  = filepath + sessionId
    file = open(filename, 'w')                          #open file for writing

    for (name,value) in dict.items():
        file.write(name + '=' + value + '\n')           #write each variable in file         

    file.close()
 
#====================================================================================