import cgitb; cgitb.enable()

from web_form import *
from html_util import *

import time

#
# Handles a new student signup. Saves the information submitted
# by the user to a log file.
#
# Also generates an HTML message to show to the user.
#

# This is what entries in the log file will look like.
LOG_ENTRY_TEMPLATE=\
"""
---------------
TIMESTAMP:      %s
NAME:           %s
EMAIL:          %s
MAJOR:          %s
CLASSES:        %s
EXPERIENCE:     %s
LANGUAGES_USED: %s
PROGRAM_LENGTH: %s
"""

# create a helper to generate the HTML
doc = HTMLDocument("Signup submission")

# get the values submitted by the user
formdata = get_submitted_form_data()

inputok = True

#
# make sure that the required fields are there and that they
# contain valid values.
#

name = formdata.get("name", "")
email = formdata.get("email", "")

# test name for validity
doc.new_paragraph()
doc.write_text("Name: ")

if not name: # only the empty string is an invalid name
    doc.write_text("Bad name.", color="red", bold=True)
    inputok = False
else:
    doc.write_text(name, color="green", bold=True)

# test email for validity
doc.new_paragraph()
doc.write_text("Email: ")

if email.find('@') < 1: # email addresses always have the '@' character
    doc.write_text("Bad email: '%s'" % email, color="red", bold=True)
    inputok = False
else:
    doc.write_text(email, color="green", bold=True, typewriter=True)

# get other fields
major = formdata.get("major", "")
classes = formdata.get("classes", "")
experience = formdata.get("experience", "")
languages = formdata.get("languages", "")
codesize = formdata.get("codesize", "")

if inputok:
    #
    # If this is a valid submission, save data to a file
    #
    # NOTE: For the open(...) and logfile.write(...) to work, you need 
    #       to run the following athena command in the parent directory
    #       of submit_signup.py.
    #
    #       athena% fs sa . daemon.scripts rliwk
    #
    #       Without running the fs command as above, your script will
    #       fail with a 'permission denied' error.
    #
    logfile = open("signup.log", "a") # open in append mode

    timestamp=time.ctime(time.time()) # get current time as a string

    logfile.write(LOG_ENTRY_TEMPLATE % (timestamp, name, email, major, classes, experience, languages, codesize))

    logfile.close()

    #
    # tell user everything is okay...
    #
    doc.new_paragraph()
    doc.write_text("You have signed up successfully.", bold=True)

    # sign up and go and look at the contents of 'signup.log' on athena.    
else:
    doc.new_paragraph()
    doc.write_text("There was a problem with the information you submitted. Please hit the back button on your browser and try again.")

#
# generate HTML
#
doc.print_html()