#!/usr/bin/python
import sys
import cgi
import menu
import re

def header(title):
	header = "Content-type: text/html\n\n"
	header = header + """<html>
	<head><title>""" + title + """</title></head>
	<body><h1>""" + title + '</h1>'

	# add modified search code here
	header = header + """<form action='search.py' method='POST'>
		<label for='sinput'>Please enter the search string:</label>
		<input type='text' name='search' id='sinput' size='30'/><br />
		<input type='submit'/><input type='reset'/>
		</form>
	"""

	return header

def footer():
	return "</body></html>"

if __name__ == '__main__':
	search = None
	form = cgi.FieldStorage()

	if (form.has_key('search')):
		alphabet = re.compile('^([^\W_]+)$')
		matches = alphabet.search(form['search'])
		if (matches):
			search = form['search']

	if (not search):
		print header('Search for food')
		print footer()
		sys.exit()

	print header('Searching for food...')
	try:
		conn = menu.connect()

		# create a Cursor object
		curs = conn.cursor()

		sql = """SELECT name, description
			FROM menu.food
			WHERE name LIKE ?"""

		# issue the SQL statement
		curs.execute(sql, search)

		# fetch the first row from the result set
		result = curs.fetchone()

		if result:
			while result:
				print("<p>Name: %s <br />Description: %s</p>\n") % (result[0], result[1])
				result = curs.fetchone()
		else:
			print "Failed to find any search results for that string."

	except Exception, e:
		print "SQL failure: %s" % e

	print footer()