#!/usr/local/bin/python
# $Id: shrink.cgi,v 1.1.1.1 1999/03/09 06:56:02 mpetullo Exp $

#   FILE: shrink.cgi -- A CGI front-end to shrink.pl
# AUTHOR: W. Michael Petullo, wp0002@drake.edu
#   DATE: 14 SEPT 1997
 
from string import splitfields, joinfields, upper
import genCGI, Pylog, PylogCGI

# HTML that will be sent when the form is not filled out completely
MissingInfoStr = """\
You did not fill out the %s field.
"""

# HTML that will be sent upon successful completion of script.
ReplyTemplate = """\
<FORM ACTION="/cgi-bin/shrink/shrink.cgi" METHOD=POSt>
<INPUT name="INPUT" size=40 value="%(INPUT)s"><BR>
<INPUT TYPE="submit" VALUE="Submit Form">

<!-- The following is the saved state -->
<input type=hidden name=STATE values="%(STATE)s">
</FORM>

%(RESPONCE)s
"""

# HTML that will be sent if Pylog fails
PylogFailure = """\
There was an error running shrink.pl.
"""

# ============================ ShrinkCGI =======================================
class ShrinkCGI (PylogCGI.PylogCGI):

	Form_data_Timeout = 10
	SingleValuedFields = ['INPUT', 'STATE']
	MultiValuedFields  = []
	
	def GenerateFillers (self, form):
	#  PRE: form.keys () == ['INPUT']
	# POST: FCTVAL = a dictionary containing the keys needed for the 
	#                responce form, ReplyTemplate
	# NOTE: The dictionary's keys contain the following:
	#                'RESPONCE' -- the responce from the shrink
		fill = {}
		try:
			self.prolog.Query ("['shrink.pl'].")
		except:
			self.prolog.Shutdown ()
			self.AbortReply ("ERROR", PylogFailure)
		input = form['INPUT']
		fill['INPUT'] = input
		input = self.PrepSentence (input)
		try:
			fill['RESPONCE'] = self.AskShrink (input)
		except:
			self.prolog.Shutdown ()
			self.AbortReply ("ERROR", PylogFailure)
		return fill
	
	def PrepSentence (self, sentence):
	#  PRE: sentence is a sentence that will eventually be sent to shrink
	# POST: FCTVAL == a sentence that will not break shrink
	# NOTE: Shrink expects something like the following:
	#       ['I','am','depressed.']
		sentence = splitfields (sentence)
		# ASSERT: s has been made a list for processing
	
		clean = []
		for word in sentence:
			word = '\'' + word + '\''
			clean.append (word)
		# ASSERT: clean is a list of words enclosed in single quotes
		clean = joinfields (clean, ",")
		# ASSERT: clean is now a string with commas seperating words
		return ("[" + clean + "]")

	def AskShrink (self, sentence):
	#  PRE: sentence is assigned something to say to the shrink
	#   &&  shrink is assigned a shrink to say it to
	# POST: FCTVAL == a responce from the shrink
		self.prolog.Query ("shrink:pick_response(%s,Resp)." % (sentence))
		self.prolog.MoreSolutions ()
		solutionDict = self.prolog.GetSolution ()
		responceList = splitfields (solutionDict['Resp'][1:-1], ',')
		# ASSERT: responceList is a list of words in reponse with
		#         leading '[' and trailing ']' removed.
		
		responce = ""
		for word in responceList:
			responce = responce + word
		responce = upper (responce[0]) + responce[1:] + '.'
		return (responce)
		
	def SingleValuedFieldAbsent(self, name):
	#  PRE: name is assigned the field which was not filled out
	# POST: MissingInfoStr is output as HTML
	#   &&  execution is terminated by raising a CGITerminate
	# NOTE: overloads ParseMixin class
		self.AbortReply ("ERROR", MissingInfoStr, name)	
	
	def AbortReply (self, title, body, str = None):
	#  PRE: title is assigned title to be written
	#   &&  body is assigned string to write as body of HTML response
	#   &&  str is assigned a string to insert in body, if neccissary
	# POST: body % str is output as HTML
	#   &&  execution is terminated by raising a CGITerminate
		if (str):
			body = body % str
		genCGI.send_reply (self.outfile, title, body)
		raise (genCGI.CGITerminate)
			
	def get_title (self):
	# POST: FCTVAL == title to be written
	# NOTE: overloads CGIbase class
		return ("Shrink")
		
	def get_body (self):
	# POST: FCTVAL == string to write as body
	# NOTE: overloads CGIbase class
		return (ReplyTemplate % self.fillers)
		
if (__name__ == "__main__"):
	ShrinkCGI ().GO ()
