#!/usr/bin/env python3
################################################################################### 
# Practice with regex using a web form
################################################################################### 
print("Content-Type: text/html \n")     #http header with newline char (required for the web)

import cgi                                      #cgi module
import re                                       #regular expression module

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

string = elements.getvalue('string') or ""      #text field from form             
regex  = elements.getvalue('regex')  or "" 
repStr = elements.getvalue('repStr') or ""      
case   = elements.getvalue('case')   or ""      

string_error = ""
regex_error  = ""
msg          = ""

#========================================================================================
# function validate: validate the html form fields 
#========================================================================================
def validate() :

    global msg;   

    if string == '' :
        msg          = 'error'     
        string_error = '*'

    if regex == '' :
        msg         = 'error'     
        regex_error = '*'

    if msg == 'error' :
        msg  = 'Please enter a string and a regex expression'
        return;    
 
    if case == '' : pattern = re.compile(regex)
    else          : pattern = re.compile(regex, re.I)                   #case insensitive

    if repStr == '' :         
        matches = pattern.search(string) 

        if matches :                                                    #if found
            msg  = "Regex expression found - " + matches.group(0) + '<br>'
            try:
                if matches.group(1) :                                             
                    msg += "  group1=" + matches.group(1)             
                if matches.group(2) :                                             
                    msg += ", group2=" + matches.group(2)
            except:
                pass
        else:
            msg  = "Regex expression not found"
     
    if repStr != '' : 
        string2 = pattern.sub(repStr, string) 
        msg     = string2                                        #replace the regex with replacement str


#========================================================================================
# function display: display the html form 
#========================================================================================
def display() :

    case_checked = ''
    if case == 'i' : case_checked = 'CHECKED';
        
    print("""
        <html>
        <head>
        <title>Python Regex Test</title>
        </head>
        <body bgcolor=lightyellow>
        <h1><center>Python Regex Test</center></h1>
        <form method=POST action="regexPractice_web.py">                           
        <fieldset style='width:485px; height:145px; border-color:gold'>
        <legend>Test a 'regex' regular expression</legend> 
        <table bgcolor=eeeeee width=485>
        <tr>
    """)
    print("<td><b>Enter any string <font color=red>" + string_error + "</font>")
    print("<td><input type=text name=string size=40 value='" + string+ "'>")
    print("<tr>")
    print("<td><b>Enter a regex... <font color=red>" + regex_error + "</font>")     
    print("<td><input type=text name=regex size=40 value='" + regex + "'>")
    print("<tr>")
    print("<td><b>Optional replace with" )    
    print("<td><input type=text name=repStr size=40 value='" + repStr + "'>")
    print("<tr>")
    print("<td><b>Case insensitive ")       
    print("<td><input type=checkbox name=case value='i' " + case_checked + ">")
    print("""
        <tr>
        <td width=150>
        <td><input type=submit value='  Regex Test  '>
        </table>
        </fieldset>
    """)
    print("<br><font color=red>" + msg + "</font>")
    print("<br>")
    print("</form>")

#========================================================================================
# main 
#========================================================================================
try:
    if string != "" or regex != "" :                #if data was collected in _POST array 
        validate() 

    display()

except Exception as e:
    import sys, traceback
    print("Content-Type: text/html \n")             #http header with newline (in case it was not done)
    print("<br>Processing Error - ", e ,'<br>')     #display processing error
    traceback.print_exc(file=sys.stdout)            #display traceback stack   




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