#!/usr/bin/env python
#=====================================================================================
# Get data from a server file
# Display to an html form
#=====================================================================================
import cgi                                      #import cgi module
import cgitb                                    #import cgi traceback module (error tracking)
import re                                       #import regular expressions module
 
cgitb.enable()
 
data = []                                       #2 dim array

elements  = cgi.FieldStorage()
sortField = elements.getvalue('sort')           #get the request sort field
sortSeq   = elements.getvalue('seq')    

print("Content-Type: text/html \n")             #required http response header (w/ extra line) 

'''===================================================================================
read_data: read data from a server file
==================================================================================='''
def read_data():
 
    global data

    file  = '/home/sultans/web/data/cust_order.file'    	#server file
    input = open(file,'r')                             	    #Open file for reading
    
    data  = input.readlines()                          	    #read entire file into array

    input.close()                                      	    #close the file

'''===================================================================================
Custom sort function
Receives a single element (a row)
Returns the column to sort on
==================================================================================='''
def sort_func(row):                             #receives an element (a row)

    if sortField=='name': return row[1]         #return the column to sort on
    if sortField=='addr': return row[2]
    if sortField=='flav': return row[3]
    if sortField=='top' : return row[4]
    if sortField=='cc'  : return row[5]
    return row[1]                               #if none, sort by name

'''===================================================================================
display: display data on the html page
==================================================================================='''
def display():

    global data, sortSeq
    
    data2 = []                              #to hold 2 dim array of data

    for rec in data:
        rec = rec.rstrip()                  #strip off trailing newline char
        fields = rec.split('||')            #turn rec into an array of fields
        data2.append(fields)                #add array to next slot of data2

#   data2.sort(key=sort_func)               #call sort_func, function must return the sort key
#   data2.sort(key=lambda data2: data2[1])  #same but using lambda unonymous function
#   data2 = sorted(data2, key=sort_func)    #same but using sorted(). Must assign to another list

#   if sortSeq is None: sortSeq='asc'
    if not sortSeq : sortSeq='asc'

    if sortSeq=='asc':
        data2.sort(key=sort_func)
        sortSeq = 'desc'
    else:
        data2.sort(key=sort_func,reverse=True)  
        sortSeq = 'asc'               

    print("""
        <html>
        <head>
        <title>Retrieve data from file and sort it</title>    
        <style>
            a     {text-decoration:none; color:brown}
            table {font:10pt arial; border:solid 2px black; border-collapse:collapse; margin-left:70px; background-color:#eeeeee; } 
            th,td {border:solid 1px black; padding-left:5px; padding-right:5px; vertical-align:top;}
        </style>
        <body bgcolor=lightyellow>
        <h1><center>The Ice Cream Shop</center></h1>
        <h2>Retrieve data from file and sort it</h2>
        <table bgcolor=lightyellow border=1>
        <tr bgcolor=tan>
    """)                          
        
    pgm_name = 'getFromFileSort_web.py'  

    print("<th><a href=" + pgm_name + "?sort=name&seq=" + sortSeq + ">Name       </a></th>")
    print("<th><a href=" + pgm_name + "?sort=addr&seq=" + sortSeq + ">Address    </a></th>")
    print("<th><a href=" + pgm_name + "?sort=flav&seq=" + sortSeq + ">Flavors    </a></th>")
    print("<th><a href=" + pgm_name + "?sort=top&seq="  + sortSeq + ">Toppings   </a></th>")
    print("<th><a href=" + pgm_name + "?sort=cc&seq="   + sortSeq + ">Credit Card</a></th>")

    for rec in data2:                                   #loop thru the data rows
        [fn,ln,addr,flav,top,cc] = rec                  #split the record on ||
        print("<tr>",end='')

        name = fn +' '+ ln
        addr = re.sub(r"__", "<br>", addr)              #replace _ with <br>
        flav = re.sub(r",",  "<br>", flav)              #replace , with <br>
        top  = re.sub(r",",  "<br>", top)               #replace , with <br>
        
        print("<td>"+ name +"<td>"+ addr +"<td>"+ flav +"<td>"+ top +"<td>"+ cc)
        print("</tr>")

    print("</table>")
    print("</body>")
    print("</html>")


'''===================================================================================
main code
==================================================================================='''
read_data();
display();



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