#!/usr/bin/env python3
#=============================================================================================
# This Python script allows a customer to login. (It validates against (table: customer)
# if user logs in with proper user/pswd --> redirect to shopping page 
# if user clicks on register button     --> redirect to registration page
#=============================================================================================
import os
import cgi                            #cgi 
import cgitb                          #cgi with traceback error handling
from urllib import parse              #for url encoding
import pymysql as mydb                #Mysql 3x database driver
import config

cgitb.enable()

msg     = ''                            	#global variables
user    = ''                            	#userid entered on screen
save    = ''                            	#save the userid?
cust_id = ''                            	#customer id used throughout the application

print('Content-type: text/html')
if config.RUN_MODE=='test': print('\n')     #if mode='test', end the headers so all output will print

#=============================================================================
# Validate that userid and password are entered
#=============================================================================
def validate_form():
    global msg

    if (not user or not pswd) :                         #if nothing is entered on screen
        msg  = 'Please enter user id and password!'     
        return

#=============================================================================
# Read pswd from the database
# validates to make sure user exists, and pswd is valid for user
#=============================================================================
def read_pswd():
    global cust_id, msg   
 
    sql = F""" SELECT cust_id, pswd, fname, lname, address 
               FROM shop_customer 
               WHERE lower(user) = '{user}' """         #not case sensitive

    try:
        conn = mydb.connect(host='localhost',user='demo2',password='demo2',database='demo2')
 
        cursor = conn.cursor()                          #create a cursor
        cursor.execute(sql);                            #execute the sql

    except mydb.Error as e:
        errorNum = e.args[0]
        errorMsg = e.args[1]
        error = 'Database Error - ' + str(errorNum) + errorMsg
        return      
       
    result = cursor.fetchall()                      #get all the rows (should only be 1 row)
    if (not result):
        msg = F"User {user} does not exist.  Please register first"
        return        

    row     = result[0]                             #take first row
    cust_id = row[0]                                #first column
    DBpswd  = row[1]
    if (pswd != DBpswd):                            #if pswd entered != database pswd
        msg = F"Password is invalid for {user}"
                            
    cursor.close()                                  #close the cursor/buffer
    conn.close()                                    #close the connection
    
#==============================================================================
# Display the HTML page  
# if there are errors, display message
#==============================================================================
def display():

    checked='checked' if save else ''               #if save user flag is on -> checked
    print(F"""
        <html>
        <head>
        <title>Shop.com</title>
        <style>
            a    {{text-decoration:none; color:brown}}
            .grn {{color:white; background-color:green; height:30px; border-radius:5px; cursor:pointer}}
            .red {{color:white; background-color:brown; height:30px; border-radius:5px; cursor:pointer}}
        </style>
        </head>

        <body bgcolor=lightyellow>
        <h1 align=center>Shop.Com</H1>

        <form method=POST >
        <fieldset style='width:350;border-color:red'>
        <legend align='left'>Sign In</legend>
        <table>
        <tr><td>Enter your user id       <td><input type=text     name=user value='{user}' >
        <tr><td>Enter your password      <td><input type=password name=pswd value='{pswd}' >
        <tr><td align=right>Save user id <td><input type=checkbox name=save value='y' {checked} >
        <tr><td><td><input type=submit value='         Sign In       ' class=grn> 
        </table>
        </fieldset>
        <br>
        <fieldset style='width:350;border-color:red'>
        <legend align='center'>Register</legend>
         <input type=button value=' Register ' class=red onClick="location.href='shopProf.py'">
        If first time user, please register
        <br><br>
        </fieldset>
        </form>
        <div style='color:red;'> {msg}   </div>
        <hr/>
        <center>
        <a href=shopProf.py>   register </a> |
        <a href=shop.py?out=y> logout   </a> |
        <a href=.>             exit     </a> 
        </center>
        </body>
        </html>
    """)

#==========================================================================
# get_cookies(): retrieve all cookies
#                return a cookies dictionary
#==========================================================================
def get_cookies():
    cookies = {}                                            #create a cookie dictionary

    cookiesStr = os.environ.get('HTTP_COOKIE')              #obtain the HTTP cookies
    if not cookiesStr: return cookies                       #if no cookies, return 

    cookiesArray = cookiesStr.split('; ')                   #split on ;
    for cookie in cookiesArray:                             #loop thru all cookies
        (name, value) = cookie.split('=',1)                 #split on first =
        value_decoded = parse.unquote(value)                #decode the value (if encoded)
        cookies[name] = value_decoded                       #cookie value (encoded)

    return cookies

#=============================================================================
# Save the cookies
#=============================================================================
def save_cookies():
    user2  = parse.quote(user)                                            #url encode the cookies

    print(F"Set-Cookie: cust_id={cust_id};  path=/")                  	  #save temporary cookies
    if save:
        print(F"Set-Cookie: cust_user={user2}; max-age=604800; path=/")   #save user cookie for 1 week                              
    if not save:
        print(F"Set-Cookie: cust_user=xyz;     max-age=-999;   path=/")   #delete the user cookie    
        
#=============================================================================
# Delete the cookies
#=============================================================================
def delete_cookies():

    print("Set-Cookie: cust_id=xyz;    max-age=-999; path=/")      #delete all temporary cookies
    if not save:
        print(F"Set-Cookie: cust_user=xyz; max-age=-999; path=/")  #delete the user cookie                                

#=====================================================================================
# main code
#=====================================================================================
input  = cgi.FieldStorage()                         #obtain the input fields from screen
user   = input.getvalue('user') or ""               #userid entry field             
pswd   = input.getvalue('pswd') or ""               #pswd entry field 
save   = input.getvalue('save') or ""               #save userid entry field 
logout = input.getvalue('out')  or ""               #logout? passed via end of url from other pages

cookies = get_cookies()                             #get the cookies

if not user:                                        #if userid is not entered
    user = cookies.get('cust_user') or ''           #check to see if user cookie exist
    if user:                                        #if exists (user opted to save the userid)
        save ='y'                                   #turn the save flag on 

if not logout:                                      #if not logging out (signing in process)
    if input:                                       #if data entered in screen
        validate_form()                             #validate field entry
        if not msg:                                 #if no validation errors
            read_pswd()                             #  check password
        if not msg:                                 #if password is valid
            save_cookies()                          #  save the cookies
            print("Location: shopBrowse.py \n")     #  redirect to shopping cart page
            exit()               
    print('\n')                                     #end of response headers
    display()                                       #display the page


if logout:                                          #if logging out (passed from another page)
    delete_cookies()                                #delete cookies
    msg = 'You have logged out successfully'
    print('\n')                                     #end of response headers
    display()                                       #display the page
    
    


#=== link to see the python code ================================================
import os
import 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
#================================================================================