#!/usr/bin/env python3
#=====================================================================================
# A typical login page using cookies 
#=====================================================================================
import cgi                           #import cgi module 
import cgitb                         #import cgi traceback module for error handling
import cookieFunc                    #for cookie processing

cgitb.enable()                       #activate the cgi traceback error handling 

print("Content-Type: text/html")     #required http response header
#print("\n")                         #end the response headers (not yet) 

msg  = ''                            #global variable

elements   = cgi.FieldStorage()                 #obtain the http parameters

user = elements.getvalue('user')  or ""         #get the user text field             
pswd = elements.getvalue('pswd')  or ""         #get the password text field 
save = elements.getvalue('save')  or ""         #get the save? checkbox

#-------------------------------------------------------------------------------------
# Function to get a single cookie
#-------------------------------------------------------------------------------------
def get_cookie(name):
   
    value = cookieFunc.getCookie(name)           #get the cookie by name
    return(value)                                #return the value

#-------------------------------------------------------------------------------------
# Function to save cookies with and without expiration date
#-------------------------------------------------------------------------------------
def save_cookies():

    print('Set-Cookie: login=yes; path=/')           #save temporary login cookie 

    if save:                                                            
        print('Set-Cookie: savedUser='+ user + '; max-age=86400; path=/')   #save user for 1 day
    else:
        print('Set-Cookie: savedUser= ; max-age=-999; path=/')              #delete user cookie
           
    
#-------------------------------------------------------------------------------------
# Function to validate entry fields 
#-------------------------------------------------------------------------------------
def validate():

    global msg                             #needed to modify global variable
                                           #no need if access to global is read only
    if user=='':
        msg = 'Please enter any userid'
    elif pswd=='': 
        msg = 'Please enter any password'

#-------------------------------------------------------------------------------------
# Function to display the form (must be defined before use)
#-------------------------------------------------------------------------------------
def display():

    print("\n")                              #end of response headers         

    print("""
        <html>
        <head>
        <title>Cookies Set</title>
        </head>
        <body bgcolor=lightyellow>
        <h1>Please Login</h1>
    """)
    print("<form method=POST name=frm action=cookieLogin.py>")                #call current script
    print(F"""  
        <fieldset style='width:340px'>
        <table>
        <tr><td>Enter user name  <td><input type=text     name=user value={user} > <i>(any)</i>
        <tr><td>Enter password   <td><input type=password name=pswd value={pswd} > <i>(any)</i>
        <tr><td>Save login user? <td><input type=checkbox name=save value=Y {saveChecked} >
        </table>
        </fieldset>
        <br>
    """)
    print("<input type=submit value=Login>")     
#   print("<input type=submit value=Login onClick='return pre_validate()'>")   #uncomment if you want to pre-validate in Javascript 
    print("</form>")
    print("<div style='color:red'>" + msg + "</div>")

    print("""                                                                  
        <script>                                //javascript validation
        function pre_validate()                 //JS pre-validate function      
        {
            user = document.frm.user.value;     //get entry values
            pswd = document.frm.pswd.value;
            if (! user || ! pswd)               //if no user or no password
            {  
                alert('Please enter any user name and password');
                return(false);                   
            }                                  
        }
        </script>
    """)

    print("</body>")
    print("</html>")
    
#-------------------------------------------------------------------------------------
# main code
#-------------------------------------------------------------------------------------

savedUser   = get_cookie('savedUser')           #get the user name from cookie (if any)
saveChecked = ''
if savedUser:                                   #if present
    if user == '':                              #if user is not entered
        user = savedUser;                       #use the saved user cookie (if any)
    saveChecked = 'CHECKED'                     #check the save checkbox    
        
if elements:                                    #if data was entered in the form
    validate()                                  #call validate function
    if msg == '':                               #if no errors
        save_cookies()                                                          #save the cookies
        print("Location: /~sultans/python/demo/5cookie/cookieShop.py?log=OK")   #redirect to another page
        print("\n")                                                             #end of response headers
        exit()

display()                                       #call display function



#=== link to see the python code ================================================
import os
import sys
sys.path.insert(0,'/home/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
#================================================================================